Files
canina/frontend/application/components/__tests__/BlogPreviewSection.test.tsx
2026-10-29 08:10:03 +00:00

162 lines
6.2 KiB
TypeScript

"use client";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import React from "react";
import BlogPreviewSection from "../BlogPreviewSection";
import api from "../../lib/services/api";
// Mock motion/react
vi.mock("motion/react", () => ({
motion: {
article: ({ children, ...props }: any) => <article {...props}>{children}</article>,
div: ({ children, ...props }: any) => <div {...props}>{children}</div>,
},
}));
// 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" />
),
}));
vi.mock("../../lib/services/api", () => ({
default: {
get: vi.fn(),
},
BASE_DOMAIN: "https://canina.ir",
}));
const mockSettings: Record<string, string> = {
blog_preview_badge: "دانشنامه و مقالات علمی",
blog_preview_title: "تازه‌ترین مقالات",
blog_preview_title_highlight: "دامپزشکی و سلامت",
blog_preview_desc: "راهنماهای علمی و کاربردی برای نگهداری و تغذیه سگ و گربه.",
blog_preview_view_all: "مشاهده همه مقالات",
blog_preview_read_article: "خواندن مقاله",
};
vi.mock("../../lib/store/settingsStore", () => ({
useSettingsStore: (selector: any) =>
selector({
getText: (key: string, fallback: string) => mockSettings[key] || fallback,
}),
}));
describe("BlogPreviewSection Component", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("renders loading skeletons initially", () => {
vi.mocked(api.get).mockReturnValue(new Promise(() => {}));
const { container } = render(<BlogPreviewSection />);
const skeletons = container.querySelectorAll(".animate-pulse");
expect(skeletons.length).toBe(3);
});
it("returns null when no blogs are returned after loading", async () => {
vi.mocked(api.get).mockResolvedValueOnce({ data: { blogs: [] } });
const { container } = render(<BlogPreviewSection />);
await waitFor(() => {
expect(container.firstChild).toBeNull();
});
});
it("renders blog cards with title, author, views, comments, and links", async () => {
const mockBlogs = [
{
id: "blog-1",
title: "اهمیت کلسیم و مفاصل در رشد توله سگ ژرمن شپرد",
slug: "calcium-joints-german-shepherd",
content: "متن مقاله...",
imageUrl: "/uploads/blogs/german-shepherd.jpg",
viewCount: 1420,
createdAt: "2026-10-10T12:00:00Z",
author: {
firstName: "دکتر مریم",
lastName: "اکبری",
},
_count: {
comments: 8,
},
},
{
id: "blog-2",
title: "علل ریزش موی فصلی در گربه‌ها و راهکارهای درمانی",
slug: "cat-hair-loss-solutions",
content: "متن مقاله ریزش مو...",
imageUrl: "https://cdn.canina.de/images/cat-fell.jpg",
viewCount: 850,
createdAt: "2026-10-11T12:00:00Z",
_count: {
comments: 3,
},
},
];
vi.mocked(api.get).mockResolvedValueOnce({ data: { blogs: mockBlogs } });
render(<BlogPreviewSection />);
await waitFor(() => {
expect(
screen.getByText("اهمیت کلسیم و مفاصل در رشد توله سگ ژرمن شپرد")
).toBeInTheDocument();
expect(
screen.getByText("علل ریزش موی فصلی در گربه‌ها و راهکارهای درمانی")
).toBeInTheDocument();
});
// Author display
expect(screen.getByText("نویسنده: دکتر مریم اکبری")).toBeInTheDocument();
// Default fallback author
expect(screen.getByText("نویسنده: کنینا")).toBeInTheDocument();
expect(screen.getAllByText("تیم: پژوهش و محتوای علمی کنینا")).toHaveLength(2);
// Verify aria-label links with full title context
const link1 = screen.getByLabelText("مطالعه مقاله: اهمیت کلسیم و مفاصل در رشد توله سگ ژرمن شپرد");
const link2 = screen.getByLabelText("مطالعه مقاله: علل ریزش موی فصلی در گربه‌ها و راهکارهای درمانی");
expect(link1).toHaveAttribute("href", "/blog/calcium-joints-german-shepherd");
expect(link2).toHaveAttribute("href", "/blog/cat-hair-loss-solutions");
});
it.each([null, undefined, "", " "])(
"renders neutral absence without an img for homepage imageUrl=%j",
async (imageUrl) => {
vi.mocked(api.get).mockResolvedValueOnce({
data: { blogs: [{
id: "no-image", slug: "no-image", title: "مقاله بدون عکس",
content: "", viewCount: 0, createdAt: "2026-01-01T00:00:00Z", imageUrl,
}] },
});
const { container } = render(<BlogPreviewSection />);
expect(await screen.findByText("مقاله بدون عکس")).toBeInTheDocument();
expect(screen.getByText("بدون تصویر")).toBeInTheDocument();
expect(container.querySelector("img")).toBeNull();
expect(api.get).toHaveBeenCalledWith("/blogs/homepage");
},
);
it("uses publication freshness and explicit byline labels on homepage cards", async () => {
vi.mocked(api.get).mockResolvedValueOnce({ data: { blogs: [{ id:"b",slug:"b",title:"B",content:"",viewCount:0,createdAt:"2026-01-01T00:00:00Z",publishedAt:"2026-01-01T00:00:00Z",contentUpdatedAt:"2026-01-02T00:00:00Z",authorTeam:"Science" }] } });
render(<BlogPreviewSection />);
expect(await screen.findByText(/تاریخ انتشار/)).toBeInTheDocument();
expect(screen.getByText(/آخرین به‌روزرسانی/)).toBeInTheDocument();
expect(screen.getByText(/نویسنده:/)).toBeInTheDocument();
expect(screen.getByText(/تیم: Science/)).toBeInTheDocument();
});
it("handles api errors gracefully and renders null", async () => {
vi.mocked(api.get).mockRejectedValueOnce(new Error("Failed to load"));
const { container } = render(<BlogPreviewSection />);
await waitFor(() => {
expect(container.firstChild).toBeNull();
});
});
});