Files
canina/frontend/application/components/__tests__/BlogPostClient.test.tsx
T

309 lines
11 KiB
TypeScript

import React from "react";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import BlogPostClient from "../BlogPostClient";
import api from "../../lib/services/api";
// Mock api
vi.mock("../../lib/services/api", () => ({
default: {
post: vi.fn(),
get: vi.fn(),
},
}));
// Mock SafeImage
vi.mock("../SafeImage", () => ({
default: ({ src, alt, className }: { src: string; alt: string; className?: string }) => (
<img src={src} alt={alt} className={className} data-testid="safe-image" />
),
}));
const mockBlog = {
id: "blog-100",
slug: "canhydrox-gag-guide",
title: "راهنمای جامع کانی‌هیدروکس GAG و ترمیم مفاصل سگ‌ها",
excerpt: "این مکمل تخصصی با تحریک ساخت کلاژن و تقویت استخوان‌ها نقش اساسی دارد.",
content: "<p>محتوای تخصصی مقاله کنینا درباره فرمولاسیون مفاصل و صدف لب‌سبز.</p>",
imageUrl: "https://example.com/blog-hero.jpg",
imageAlt: "تصویر کانی‌هیدروکس GAG",
imageCaption: "بسته‌بندی قوطی کانی‌هیدروکس",
readingTime: 6,
viewCount: 1540,
allowComments: true,
category: {
id: "cat-joints",
name: "سلامت استخوان و مفاصل",
},
tags: [
{ id: "t-1", name: "مفصل_ساز" },
{ id: "t-2", name: "کلسیم" },
"صدف_لب_سبز",
],
comments: [
{
id: "c-1",
authorName: "دکتر مریم احمدی",
content: "برای سگ ژرمن ۴ ماهه دوز پیشنهادی به چه شکل است؟",
createdAt: "2026-03-01T10:00:00Z",
},
],
relatedProducts: [
{
id: "prod-1",
slug: "canhydrox-gag-tablets",
nameFa: "قرص کانی‌هیدروکس GAG",
category: { name: "مفاصل" },
imageUrl: "/assets/images/canhydrox.png",
priceValue: 1850000,
},
],
relatedBlogs: [
{
id: "rel-blog-1",
slug: "calcium-dosages",
title: "دوز مصرفی کلسیم در نژادهای بزرگ",
readingTime: 4,
imageUrl: "/assets/images/calcium.png",
},
],
};
describe("BlogPostClient Component", () => {
beforeEach(() => {
vi.clearAllMocks();
sessionStorage.clear();
vi.mocked(api.post).mockResolvedValue({ data: { viewCount: 1541 } });
});
it("renders blog title, author, category, reading time, excerpt, sanitized content, and tags", async () => {
render(
<BlogPostClient
blog={mockBlog}
sanitizedContent={mockBlog.content}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
);
// Breadcrumb and headers
expect(screen.getByRole("heading", { level: 1, name: /راهنمای جامع کانی‌هیدروکس GAG/ })).toBeInTheDocument();
expect(screen.getAllByText("سلامت استخوان و مفاصل").length).toBeGreaterThan(0);
expect(screen.getByText("نویسنده: دکتر توماس بکر")).toBeInTheDocument();
expect(screen.getByText("۱۵ فروردین ۱۴۰۵")).toBeInTheDocument();
expect(screen.getAllByText(/دقیقه مطالعه/).length).toBeGreaterThan(0);
// Excerpt and HTML content
expect(
screen.getByText("این مکمل تخصصی با تحریک ساخت کلاژن و تقویت استخوان‌ها نقش اساسی دارد.")
).toBeInTheDocument();
expect(
screen.getByText("محتوای تخصصی مقاله کنینا درباره فرمولاسیون مفاصل و صدف لب‌سبز.")
).toBeInTheDocument();
// Tags
expect(screen.getByText("#مفصل_ساز")).toBeInTheDocument();
expect(screen.getByText("#کلسیم")).toBeInTheDocument();
expect(screen.getByText("#صدف_لب_سبز")).toBeInTheDocument();
// Image caption
expect(screen.getByText("بسته‌بندی قوطی کانی‌هیدروکس")).toBeInTheDocument();
});
it("renders semantic publication, valid update and explicit author/team labels", () => {
render(<BlogPostClient blog={{...mockBlog,publishedAt:"2026-01-01T00:00:00Z",contentUpdatedAt:"2026-01-02T00:00:00Z",authorTeam:"Science"}} sanitizedContent={mockBlog.content} publishedDate="۱۲ دی ۱۴۰۴" authorName="دکتر بکر" />);
expect(screen.getByText(/تاریخ انتشار/)).toBeInTheDocument();
expect(screen.getByText(/آخرین به‌روزرسانی/)).toBeInTheDocument();
expect(screen.getByText(/نویسنده: دکتر بکر/)).toBeInTheDocument();
expect(screen.getByText(/تیم: Science/)).toBeInTheDocument();
expect(document.querySelectorAll("time[datetime]").length).toBe(2);
});
it("registers blog view count on mount via API", async () => {
render(
<BlogPostClient
blog={mockBlog}
sanitizedContent={mockBlog.content}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
);
await waitFor(() => {
expect(api.post).toHaveBeenCalledWith(
`/blogs/${encodeURIComponent(mockBlog.slug)}/view`
);
});
await waitFor(() => {
expect(screen.getByText(/۱٬۵۴۱ بازدید/)).toBeInTheDocument();
});
});
it("renders related products and related blogs in sidebars", () => {
render(
<BlogPostClient
blog={mockBlog}
sanitizedContent={mockBlog.content}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
);
// Related Products
expect(screen.getByText("مکمل‌های مرتبط این مقاله")).toBeInTheDocument();
expect(screen.getAllByText("قرص کانی‌هیدروکس GAG").length).toBeGreaterThan(0);
expect(screen.getByText(/۱٬۸۵۰٬۰۰۰ تومان/)).toBeInTheDocument();
// Related Blogs
expect(screen.getByText("مقالات پیشنهادی")).toBeInTheDocument();
expect(screen.getByText("دوز مصرفی کلسیم در نژادهای بزرگ")).toBeInTheDocument();
expect(screen.getAllByText(/دقیقه مطالعه/).length).toBeGreaterThan(0);
// Scientific Consultation CTA
expect(screen.getByText("نیاز به راهنمایی و دوز درمانی دارید؟")).toBeInTheDocument();
expect(screen.getByRole("button", { name: /مشاوره هوشمند دارویی/ })).toBeInTheDocument();
});
it("renders existing comments and handles new comment submission successfully", async () => {
vi.mocked(api.post).mockImplementation(async (url: string) => {
if (url.includes("/view")) {
return { data: { viewCount: 1541 } };
}
if (url.includes("/comments")) {
return { data: { success: true } };
}
return { data: {} };
});
render(
<BlogPostClient
blog={mockBlog}
sanitizedContent={mockBlog.content}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
);
// Check existing comment
expect(screen.getByText("دکتر مریم احمدی")).toBeInTheDocument();
expect(
screen.getByText("برای سگ ژرمن ۴ ماهه دوز پیشنهادی به چه شکل است؟")
).toBeInTheDocument();
// Submit new comment
const nameInput = screen.getByPlaceholderText("نام و نام خانوادگی...");
const emailInput = screen.getByPlaceholderText("آدرس ایمیل...");
const textarea = screen.getByPlaceholderText("متن دیدگاه شما...");
const submitBtn = screen.getByRole("button", { name: /ارسال نظر/ });
fireEvent.change(nameInput, { target: { value: "علی رضایی" } });
fireEvent.change(emailInput, { target: { value: "ali@example.com" } });
fireEvent.change(textarea, { target: { value: "آیا برای گربه‌ها هم قابل استفاده است؟" } });
fireEvent.click(submitBtn);
await waitFor(() => {
expect(api.post).toHaveBeenCalledWith(
`/blogs/${encodeURIComponent(mockBlog.slug)}/comments`,
{
userName: "علی رضایی",
email: "ali@example.com",
content: "آیا برای گربه‌ها هم قابل استفاده است؟",
}
);
});
await waitFor(() => {
expect(
screen.getByText(/دیدگاه شما با موفقیت ثبت شد و پس از بررسی و تایید تیم علمی/)
).toBeInTheDocument();
});
});
it("handles empty fields without submitting comments", async () => {
render(
<BlogPostClient
blog={mockBlog}
sanitizedContent={mockBlog.content}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
);
const submitBtn = screen.getByRole("button", { name: /ارسال نظر/ });
fireEvent.click(submitBtn);
expect(api.post).not.toHaveBeenCalledWith(
expect.stringContaining("/comments"),
expect.anything()
);
});
it("copies URL to clipboard when navigator.share is unavailable", async () => {
const writeTextMock = vi.fn().mockResolvedValue(undefined);
Object.assign(navigator, {
clipboard: {
writeText: writeTextMock,
},
share: undefined,
});
render(
<BlogPostClient
blog={mockBlog}
sanitizedContent={mockBlog.content}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
);
const shareBtn = screen.getByRole("button", { name: /اشتراک‌گذاری/ });
fireEvent.click(shareBtn);
expect(writeTextMock).toHaveBeenCalled();
await waitFor(() => {
expect(screen.getByText("لینک کپی شد!")).toBeInTheDocument();
});
});
it("renders the server-sanitized article HTML instead of recomputing content in the browser", () => {
const rawContent = "<!--metaTitle: hidden--><p>متن خام متفاوت</p><script>alert(1)</script>";
const sanitizedContent = "<p>اگر بچه‌گربه‌ای یتیم پیدا کرده‌اید</p><h2>راهنمای تغذیه</h2>";
const { container } = render(
<BlogPostClient
blog={{ ...mockBlog, content: rawContent }}
sanitizedContent={sanitizedContent}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
);
const article = container.querySelector('.article-html-content');
expect(article?.innerHTML).toBe(sanitizedContent);
expect(article).toHaveTextContent('اگر بچه‌گربه‌ای یتیم پیدا کرده‌اید');
expect(article?.innerHTML).not.toContain('metaTitle');
expect(article?.innerHTML).not.toContain('<script');
});
it("renders in-article product cards when content has product markers", () => {
const contentWithMarker = `<p>توضیحات مهم درباره آرتروز سگ‌ها:</p><p>[product canhydrox-gag-tablets]</p><p>توضیحات تکمیلی</p>`;
render(
<BlogPostClient
blog={mockBlog}
sanitizedContent={contentWithMarker}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
);
expect(screen.getByTestId("article-product-card")).toBeInTheDocument();
expect(screen.getAllByText("قرص کانی‌هیدروکس GAG").length).toBeGreaterThan(0);
expect(screen.getByText("ضمانت ۱۰۰٪ اصالت آلمان")).toBeInTheDocument();
});
});