Files
canina/frontend/application/app/blog/[slug]/blog-slug-page.test.tsx
T

161 lines
7.1 KiB
TypeScript

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import BlogPostPage, { generateMetadata } from './page';
vi.mock('../../../lib/seo', () => ({
getSeoConfig: vi.fn().mockResolvedValue({
brandNameFa: 'کنینا ایران',
canonicalBaseUrl: 'https://canina.ir',
ogImageUrl: '/assets/og.jpg',
defaultMetaDescription: 'توضیحات پیش‌فرض',
titleSeparator: '|',
titlePosition: 'suffix',
}),
formatPageTitle: vi.fn((title) => `${title} | کنینا ایران`),
}));
vi.mock('../../../components/BlogPostClient', () => ({
default: ({ authorName, authorTeam }: { authorName: string; authorTeam: string }) => (
<div data-testid="blog-post-client">نویسنده: {authorName} تیم: {authorTeam}</div>
),
}));
describe('BlogPostPage FAQPage Schema injection (SEO-P1-07)', () => {
beforeEach(() => {
vi.stubEnv('INTERNAL_API_URL', 'http://backend:3000/api');
vi.stubEnv('NEXT_PUBLIC_SITE_URL', 'https://canina.ir');
});
afterEach(() => {
vi.unstubAllGlobals();
vi.unstubAllEnvs();
});
it('injects FAQPage JSON-LD schema when article contains questions and answers', async () => {
const blogData = {
slug: 'joint-health',
title: 'سلامت مفاصل سگ',
content: `
<article>
<p>مقدمه‌ای درباره مفاصل سگ.</p>
<details>
<summary>آیا این مکمل برای سگ مسن مناسب است؟</summary>
<p>بله، بسیار توصیه می‌شود و روند تخریب مفصل را کند می‌کند.</p>
</details>
</article>
`,
createdAt: '2026-01-01',
publishedAt: '2026-01-01',
};
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok: true,
json: async () => blogData,
})
);
const jsx = await BlogPostPage({ params: Promise.resolve({ slug: 'joint-health' }) });
expect(jsx).toBeDefined();
// Verify scripts in JSX tree
const scripts = React.Children.toArray(jsx.props.children).filter(
(child: any) => child?.type === 'script' && child?.props?.['type'] === 'application/ld+json'
);
// There should be 3 schemas: Article, Breadcrumb, and FAQPage
expect(scripts.length).toBe(3);
const faqScript: any = scripts.find((s: any) => s.props['data-testid'] === 'faq-schema');
expect(faqScript).toBeDefined();
const faqJson = JSON.parse(faqScript.props.dangerouslySetInnerHTML.__html);
expect(faqJson['@type']).toBe('FAQPage');
expect(faqJson.mainEntity).toHaveLength(1);
expect(faqJson.mainEntity[0].name).toBe('آیا این مکمل برای سگ مسن مناسب است؟');
});
it('uses explicit same-day material freshness for dateModified and ignores technical updatedAt', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ok:true,json:async()=>({slug:'fresh',title:'Fresh',content:'<p>x</p>',publishedAt:'2026-01-01T01:00:00Z',updatedAt:'2026-01-01T10:00:00Z',contentUpdatedAt:'2026-01-01T12:00:00Z'})}));
const jsx=await BlogPostPage({params:Promise.resolve({slug:'fresh'})}); const script:any=React.Children.toArray(jsx.props.children)[0]; const json=JSON.parse(script.props.dangerouslySetInnerHTML.__html); expect(json.dateModified).toBe('2026-01-01T12:00:00.000Z'); expect(json.author['@type']).toBe('Organization'); expect(json.author.name).toBe('کنینا');
});
it('uses publication as dateModified when only technical updatedAt exists', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ok:true,json:async()=>({slug:'technical',title:'Technical',content:'<p>x</p>',publishedAt:'2026-01-01T01:00:00Z',updatedAt:'2026-01-01T12:00:00Z',contentUpdatedAt:null})}));
const jsx=await BlogPostPage({params:Promise.resolve({slug:'technical'})}); const script:any=React.Children.toArray(jsx.props.children)[0]; const json=JSON.parse(script.props.dangerouslySetInnerHTML.__html); expect(json.dateModified).toBe('2026-01-01T01:00:00.000Z');
});
it('uses the stable Organization fallback visibly and in metadata', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({
slug: 'authorless', title: 'Authorless', content: '<p>x</p>', publishedAt: '2026-01-01T00:00:00Z', author: { firstName: '', lastName: '' },
}) }));
const metadata = await generateMetadata({ params: Promise.resolve({ slug: 'authorless' }) });
expect((metadata.openGraph as any)?.authors).toEqual(['کنینا']);
const jsx = await BlogPostPage({ params: Promise.resolve({ slug: 'authorless' }) });
const children = React.Children.toArray(jsx.props.children) as any[];
const client = children.find((child) => child?.props?.authorName);
expect(client.props.authorName).toBe('کنینا');
const article = JSON.parse(children[0].props.dangerouslySetInnerHTML.__html);
expect(article.author).toMatchObject({
'@type': 'Organization',
name: 'کنینا',
});
});
it('uses a custom authorTeam as the authorless Organization identity in metadata and rendering', async () => {
const organizationName = 'تیم دامپزشکی کنینا';
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({
slug: 'custom-team',
title: 'Custom team article',
content: '<p>x</p>',
publishedAt: '2026-01-01T00:00:00Z',
author: null,
authorTeam: organizationName,
}) }));
const metadata = await generateMetadata({ params: Promise.resolve({ slug: 'custom-team' }) });
expect((metadata.openGraph as any)?.authors).toEqual(['کنینا']);
const jsx = await BlogPostPage({ params: Promise.resolve({ slug: 'custom-team' }) });
const children = React.Children.toArray(jsx.props.children) as any[];
const article = JSON.parse(children[0].props.dangerouslySetInnerHTML.__html);
expect(article.author).toMatchObject({ '@type': 'Organization', name: 'کنینا' });
const html = renderToStaticMarkup(jsx);
expect(html).toContain('نویسنده: کنینا');
expect(html).toContain(`تیم: ${organizationName}`);
});
it('does not inject FAQPage schema when article does not have FAQs', async () => {
const blogData = {
slug: 'nutrition',
title: 'تغذیه سگ',
content: '<p>یک مقاله ساده بدون سوال و جواب یا آکاردئون.</p>',
createdAt: '2026-01-01',
publishedAt: '2026-01-01',
};
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok: true,
json: async () => blogData,
})
);
const jsx = await BlogPostPage({ params: Promise.resolve({ slug: 'nutrition' }) });
const scripts = React.Children.toArray(jsx.props.children).filter(
(child: any) => child?.type === 'script' && child?.props?.['type'] === 'application/ld+json'
);
// Only Article and Breadcrumb schemas
expect(scripts.length).toBe(2);
const faqScript = scripts.find((s: any) => s.props['data-testid'] === 'faq-schema');
expect(faqScript).toBeUndefined();
});
});