350 lines
11 KiB
TypeScript
350 lines
11 KiB
TypeScript
"use client";
|
|
import React from "react";
|
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
|
import ArchivePage, { orderProductsByAvailability } from "../ArchivePage";
|
|
import { productService } from "../../lib/services/productService";
|
|
import { useCartStore } from "../../lib/store/cartStore";
|
|
import { usePetStore } from "../../lib/store/usePetStore";
|
|
import { useSettingsStore } from "../../lib/store/settingsStore";
|
|
import { useCatalogMode } from "../../lib/useCatalogMode";
|
|
|
|
// Mock next/navigation
|
|
const mockPush = vi.fn();
|
|
const mockReplace = vi.fn();
|
|
vi.mock("next/navigation", () => ({
|
|
useRouter: () => ({
|
|
push: mockPush,
|
|
replace: mockReplace,
|
|
}),
|
|
}));
|
|
|
|
// Mock productService
|
|
vi.mock("../../lib/services/productService", () => ({
|
|
productService: {
|
|
getActiveFilters: vi.fn(),
|
|
getBanners: vi.fn(),
|
|
getProducts: vi.fn(),
|
|
},
|
|
}));
|
|
|
|
// Mock stores
|
|
vi.mock("../../lib/store/cartStore", () => ({
|
|
useCartStore: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("../../lib/store/usePetStore", () => ({
|
|
usePetStore: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("../../lib/store/settingsStore", () => ({
|
|
useSettingsStore: vi.fn((selector) => {
|
|
const state = {
|
|
getText: (_k: string, def: string) => def,
|
|
};
|
|
if (typeof selector === "function") {
|
|
return selector(state);
|
|
}
|
|
return state;
|
|
}),
|
|
}));
|
|
|
|
vi.mock("../../lib/useCatalogMode", () => ({
|
|
useCatalogMode: vi.fn(() => ({
|
|
showPrices: true,
|
|
allowCart: true,
|
|
showPreorderBtn: false,
|
|
})),
|
|
}));
|
|
|
|
// Mock motion/react
|
|
vi.mock("motion/react", () => ({
|
|
motion: {
|
|
div: ({ children, layout, initial, animate, ...props }: any) => <div {...props}>{children}</div>,
|
|
},
|
|
AnimatePresence: ({ children }: any) => <>{children}</>,
|
|
}));
|
|
|
|
// Mock SafeImage
|
|
vi.mock("../SafeImage", () => ({
|
|
default: ({ alt, src }: any) => <img alt={alt} src={src} data-testid="safe-image" />,
|
|
}));
|
|
|
|
// Mock BannerPlacement
|
|
vi.mock("../BannerPlacement", () => ({
|
|
default: ({ position }: any) => <div data-testid={`banner-${position}`} />,
|
|
}));
|
|
|
|
const mockProducts = [
|
|
{
|
|
id: "prod-1",
|
|
name: "Pet Glucosamine",
|
|
nameFa: "گلوکوزامین مفاصل",
|
|
nameEn: "Pet Glucosamine",
|
|
slug: "pet-glucosamine",
|
|
category: "joints",
|
|
price: "150,000 تومان",
|
|
priceValue: 150000,
|
|
suitableFor: "سگ",
|
|
image: "/images/prod1.png",
|
|
symptoms: ["درد مفاصل"],
|
|
},
|
|
{
|
|
id: "prod-2",
|
|
name: "Immune Booster",
|
|
nameFa: "تقویت کننده ایمنی",
|
|
nameEn: "Immune Booster",
|
|
slug: "immune-booster",
|
|
category: "immune",
|
|
price: "220,000 تومان",
|
|
priceValue: 220000,
|
|
suitableFor: "گربه",
|
|
image: "/images/prod2.png",
|
|
symptoms: ["ضعف بعد از بیماری"],
|
|
},
|
|
{
|
|
id: "prod-3",
|
|
name: "Energy Vitamin",
|
|
nameFa: "ویتامین و انرژیبخش",
|
|
nameEn: "Energy Vitamin",
|
|
slug: "energy-vitamin",
|
|
category: "energy",
|
|
price: "90,000 تومان",
|
|
priceValue: 90000,
|
|
suitableFor: "هر دو",
|
|
image: "/images/prod3.png",
|
|
symptoms: ["بیاشتهایی"],
|
|
},
|
|
];
|
|
|
|
it("puts available products first while preserving descending-price sort order within groups", () => {
|
|
const sortedByPriceDesc = [
|
|
{ id: "out-high", stock: 0 },
|
|
{ id: "in-mid", stock: 5 },
|
|
{ id: "in-low", stock: 2 },
|
|
{ id: "out-low", stock: 0 },
|
|
] as any;
|
|
|
|
expect(orderProductsByAvailability(sortedByPriceDesc).map(product => product.id)).toEqual([
|
|
"in-mid", "in-low", "out-high", "out-low",
|
|
]);
|
|
});
|
|
|
|
it("puts available products first while preserving ascending-price sort order and groups status fields", () => {
|
|
const sortedByPriceAsc = [
|
|
{ id: "in-low", stockStatus: "IN_STOCK" },
|
|
{ id: "out-mid", stockStatus: "OUT_OF_STOCK" },
|
|
{ id: "in-high", stockStatus: "IN_STOCK" },
|
|
{ id: "out-discontinued", stockStatus: "DISCONTINUED" },
|
|
] as any;
|
|
|
|
expect(orderProductsByAvailability(sortedByPriceAsc).map(product => product.id)).toEqual([
|
|
"in-low", "in-high", "out-mid", "out-discontinued",
|
|
]);
|
|
});
|
|
|
|
describe("ArchivePage Component", () => {
|
|
it("renders server-provided initial products without waiting for a client fetch", () => {
|
|
render(<ArchivePage initialProducts={mockProducts as any} />);
|
|
|
|
expect(screen.getAllByText("گلوکوزامین مفاصل").length).toBeGreaterThan(0);
|
|
expect(productService.getProducts).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("gives catalog search controls accessible names", () => {
|
|
render(<ArchivePage initialProducts={mockProducts as any} />);
|
|
|
|
expect(screen.getAllByLabelText("جستجوی محصول").length).toBe(2);
|
|
expect(screen.getAllByLabelText("جستجوی علائم").length).toBeGreaterThan(0);
|
|
});
|
|
|
|
it("gives the catalog sort control an accessible name", () => {
|
|
render(<ArchivePage initialProducts={mockProducts as any} />);
|
|
|
|
expect(screen.getByLabelText("مرتبسازی محصولات")).toBeTruthy();
|
|
});
|
|
|
|
it("exposes a scroll affordance for the mobile filter row", () => {
|
|
render(<ArchivePage initialProducts={mockProducts as any} />);
|
|
|
|
const filterRow = screen.getByTestId("mobile-catalog-filters");
|
|
expect(filterRow).toHaveAttribute("aria-label", "فیلترهای محصولات");
|
|
expect(screen.getByTestId("mobile-catalog-filters-edge")).toBeInTheDocument();
|
|
});
|
|
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
|
|
vi.mocked(useCartStore).mockReturnValue({
|
|
items: [],
|
|
addItem: vi.fn(),
|
|
} as any);
|
|
|
|
vi.mocked(usePetStore).mockReturnValue({
|
|
pets: [],
|
|
activePetId: null,
|
|
} as any);
|
|
|
|
vi.mocked(productService.getActiveFilters).mockResolvedValue({
|
|
categories: [
|
|
{ slug: "joints", name: "مفاصل و استخوان" },
|
|
{ slug: "immune", name: "تقویت سیستم ایمنی" },
|
|
],
|
|
symptoms: ["درد مفاصل", "ضعف بعد از بیماری", "بیاشتهایی"],
|
|
} as any);
|
|
|
|
vi.mocked(productService.getBanners).mockResolvedValue([] as any);
|
|
|
|
vi.mocked(productService.getProducts).mockResolvedValue({
|
|
data: mockProducts,
|
|
} as any);
|
|
});
|
|
|
|
it("renders product listing grid and top banner placement", async () => {
|
|
render(<ArchivePage />);
|
|
|
|
expect(screen.getByTestId("banner-shop_top")).toBeInTheDocument();
|
|
|
|
await waitFor(() => {
|
|
const items = screen.getAllByText("گلوکوزامین مفاصل");
|
|
expect(items.length).toBeGreaterThan(0);
|
|
});
|
|
});
|
|
|
|
it("refreshes products from the mobile catalog search control", async () => {
|
|
render(<ArchivePage initialProducts={mockProducts as any} />);
|
|
|
|
const mobileSearch = screen.getByTestId("shop-search-input-mobile");
|
|
fireEvent.change(mobileSearch, { target: { value: "گلوکوزامین" } });
|
|
|
|
await waitFor(() => {
|
|
expect(productService.getProducts).toHaveBeenCalledWith(
|
|
expect.objectContaining({ query: "گلوکوزامین" })
|
|
);
|
|
});
|
|
});
|
|
|
|
it("filters products by search query input", async () => {
|
|
render(<ArchivePage />);
|
|
|
|
await waitFor(() => {
|
|
const items = screen.getAllByText("گلوکوزامین مفاصل");
|
|
expect(items.length).toBeGreaterThan(0);
|
|
});
|
|
|
|
const searchInput = screen.getByTestId("shop-search-input");
|
|
fireEvent.change(searchInput, { target: { value: "گلوکوزامین" } });
|
|
|
|
await waitFor(() => {
|
|
expect(productService.getProducts).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
query: "گلوکوزامین",
|
|
})
|
|
);
|
|
});
|
|
});
|
|
|
|
it("updates category filter when category pill is selected", async () => {
|
|
render(<ArchivePage />);
|
|
|
|
await waitFor(() => {
|
|
expect(screen.getByText("مفاصل و استخوان")).toBeInTheDocument();
|
|
});
|
|
|
|
// Click category filter pill
|
|
const categoryButton = screen.getByText("مفاصل و استخوان");
|
|
fireEvent.click(categoryButton);
|
|
|
|
await waitFor(() => {
|
|
expect(productService.getProducts).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
category: "joints",
|
|
})
|
|
);
|
|
});
|
|
});
|
|
|
|
it("handles sorting options selection", async () => {
|
|
render(<ArchivePage />);
|
|
|
|
await waitFor(() => {
|
|
const items = screen.getAllByText("گلوکوزامین مفاصل");
|
|
expect(items.length).toBeGreaterThan(0);
|
|
});
|
|
|
|
const sortSelects = screen.getAllByRole("combobox");
|
|
const desktopSort = sortSelects[0];
|
|
|
|
fireEvent.change(desktopSort, { target: { value: "priceValue:asc" } });
|
|
|
|
await waitFor(() => {
|
|
expect(productService.getProducts).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
sortBy: "priceValue",
|
|
sortOrder: "asc",
|
|
})
|
|
);
|
|
});
|
|
});
|
|
|
|
it("displays empty state when no products match filters", async () => {
|
|
vi.mocked(productService.getProducts).mockResolvedValue({
|
|
data: [],
|
|
} as any);
|
|
|
|
render(<ArchivePage />);
|
|
|
|
await waitFor(() => {
|
|
expect(screen.getByText("محصولی یافت نشد!")).toBeInTheDocument();
|
|
expect(
|
|
screen.getByText(
|
|
"با فیلترهای فعلی محصولی مطابق با نیاز شما پیدا نکردیم. لطفاً فیلترها را گستردهتر کنید یا دکمه ریست را بزنید."
|
|
)
|
|
).toBeInTheDocument();
|
|
});
|
|
});
|
|
|
|
it("clears active filters when reset button is clicked in empty state", async () => {
|
|
vi.mocked(productService.getProducts).mockResolvedValue({
|
|
data: [],
|
|
} as any);
|
|
|
|
render(<ArchivePage initialCategory="joints" />);
|
|
|
|
await waitFor(() => {
|
|
expect(screen.getByText("محصولی یافت نشد!")).toBeInTheDocument();
|
|
});
|
|
|
|
const resetBtn = screen.getByText("پاک کردن همه فیلترها و نمایش همه");
|
|
fireEvent.click(resetBtn);
|
|
|
|
expect(mockPush).toHaveBeenCalledWith("/shop");
|
|
});
|
|
|
|
it("renders exactly one card instance per product in list viewMode to avoid DOM duplication across breakpoints", async () => {
|
|
const singleProduct = {
|
|
id: "prod-single-1",
|
|
slug: "canina-prod-single",
|
|
name: "محصول آزمایشی یکتا",
|
|
nameFa: "محصول آزمایشی یکتا",
|
|
priceValue: 120000,
|
|
stock: 10,
|
|
categorySlug: "joints",
|
|
images: ["/test.png"],
|
|
symptoms: [],
|
|
main_ingredients: [],
|
|
};
|
|
|
|
render(<ArchivePage initialProducts={[singleProduct as any]} />);
|
|
|
|
await waitFor(() => {
|
|
expect(screen.getAllByText("محصول آزمایشی یکتا").length).toBeGreaterThan(0);
|
|
});
|
|
|
|
const productLinks = screen.getAllByRole("link", { name: /محصول آزمایشی یکتا/i });
|
|
expect(productLinks).toHaveLength(1);
|
|
});
|
|
|
|
});
|