test: comprehensive test suites and quality gates pass across backend, storefront and admin
- Backend (NestJS): 82 suites, 641 tests passing; 0 ESLint errors; 0 tsc errors. Hardened SSL cert/key matching, SSRF IP pinning, and eBank validation. - Admin Panel (Vite/React): 48 suites, 300 tests passing; 0 ESLint errors; 0 tsc errors. Full coverage across all pages and settings. - Storefront (Next.js): 62 suites, 368 tests passing; 0 ESLint errors; 0 tsc errors. - Fixed unmount lifecycle guards, promise error handling, and component edge cases.
This commit is contained in:
1 parent
1e73715169
commit
ddbf1ca026
439 files changed
+32911
-6107
No files matched your search
@@ -70,7 +70,8 @@ export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsD
|
||||
t.async = 1;
|
||||
t.src = 'https://www.clarity.ms/tag/' + i;
|
||||
const y = l.getElementsByTagName(r)[0];
|
||||
y.parentNode.insertBefore(t, y);
|
||||
if (y?.parentNode) y.parentNode.insertBefore(t, y);
|
||||
else l.head.appendChild(t);
|
||||
})(window, document, 'clarity', 'script', clarityId);
|
||||
}
|
||||
};
|
||||
@@ -82,16 +83,19 @@ export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsD
|
||||
window.addEventListener('keydown', loadAnalytics, { passive: true, once: true });
|
||||
|
||||
// Fallback: idle execution after 3.5s
|
||||
let idleId: number | undefined;
|
||||
const timer = setTimeout(() => {
|
||||
if (typeof window !== 'undefined' && 'requestIdleCallback' in window) {
|
||||
(window as any).requestIdleCallback(loadAnalytics, { timeout: 2000 });
|
||||
idleId = window.requestIdleCallback(loadAnalytics, { timeout: 2000 });
|
||||
} else {
|
||||
loadAnalytics();
|
||||
}
|
||||
}, 3500);
|
||||
|
||||
return () => {
|
||||
loaded = true;
|
||||
clearTimeout(timer);
|
||||
if (idleId !== undefined) window.cancelIdleCallback(idleId);
|
||||
window.removeEventListener('scroll', loadAnalytics);
|
||||
window.removeEventListener('touchstart', loadAnalytics);
|
||||
window.removeEventListener('mousemove', loadAnalytics);
|
||||
|
||||
@@ -30,8 +30,13 @@ export default function B2BPortal({ onClose }: { onClose: () => void }) {
|
||||
|
||||
const isWholesaleVerified = (role as string) === "User_Wholesale" || (role as string) === "ADMIN" || (role as string) === "User_Partner";
|
||||
|
||||
const [loadError, setLoadError] = useState(false);
|
||||
useEffect(() => {
|
||||
productService.getProducts({ limit: 999 }).then(res => setProducts(res.data));
|
||||
let active = true;
|
||||
productService.getProducts({ limit: 999 })
|
||||
.then(res => { if (active) setProducts(res.data); })
|
||||
.catch(() => { if (active) setLoadError(true); });
|
||||
return () => { active = false; };
|
||||
}, []);
|
||||
|
||||
const filteredProducts = products.filter(p =>
|
||||
@@ -181,6 +186,7 @@ export default function B2BPortal({ onClose }: { onClose: () => void }) {
|
||||
|
||||
{/* Table */}
|
||||
<div className="flex-1 overflow-y-auto p-8">
|
||||
{loadError && <p role="alert">خطا در دریافت محصولات. لطفاً دوباره تلاش کنید.</p>}
|
||||
<div className="bg-white border border-medical-gray-200 rounded-3xl overflow-hidden shadow-sm">
|
||||
<table className="w-full text-right">
|
||||
<thead className="bg-medical-gray-50 border-b border-medical-gray-200">
|
||||
|
||||
@@ -245,6 +245,8 @@ export default function CheckoutPage() {
|
||||
return;
|
||||
} else {
|
||||
toast.error("خطا در ایجاد تراکنش پرداخت زیبال");
|
||||
router.push(`/checkout/success/${orderId}`);
|
||||
return;
|
||||
}
|
||||
} catch (gatewayErr: unknown) {
|
||||
const gErr = gatewayErr as { response?: { data?: { message?: string } }; message?: string };
|
||||
|
||||
@@ -76,7 +76,10 @@ export default function PodcastInlinePlayer({ podcast }: PodcastInlinePlayerProp
|
||||
const togglePlay = useCallback(() => {
|
||||
if (!audioRef.current) return;
|
||||
if (audioRef.current.paused) {
|
||||
audioRef.current.play().catch(console.error);
|
||||
audioRef.current.play().catch((error: unknown) => {
|
||||
setIsPlaying(false);
|
||||
console.error(error);
|
||||
});
|
||||
setIsPlaying(true);
|
||||
} else {
|
||||
audioRef.current.pause();
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
"use client";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import AddressModal, { validateAddressForm, normalizeDigits } from "../AddressModal";
|
||||
|
||||
describe("AddressModal & Address Validation", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("normalizeDigits", () => {
|
||||
it("should correctly convert Persian and Arabic digits to English digits", () => {
|
||||
expect(normalizeDigits("۰۹۱۲۳۴۵۶۷۸۹")).toBe("09123456789");
|
||||
expect(normalizeDigits("٠١٢٣٤٥٦٧٨٩")).toBe("0123456789");
|
||||
expect(normalizeDigits("12345")).toBe("12345");
|
||||
expect(normalizeDigits("")).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("validateAddressForm", () => {
|
||||
it("should return errors for missing required fields", () => {
|
||||
const emptyForm = {
|
||||
title: "",
|
||||
receptorName: "",
|
||||
phone: "",
|
||||
province: "",
|
||||
city: "",
|
||||
detail: "",
|
||||
zipCode: "",
|
||||
isDefault: false,
|
||||
};
|
||||
|
||||
const errors = validateAddressForm(emptyForm);
|
||||
expect(errors.title).toBeDefined();
|
||||
expect(errors.receptorName).toBeDefined();
|
||||
expect(errors.phone).toBeDefined();
|
||||
expect(errors.province).toBeDefined();
|
||||
expect(errors.city).toBeDefined();
|
||||
expect(errors.detail).toBeDefined();
|
||||
expect(errors.zipCode).toBeDefined();
|
||||
});
|
||||
|
||||
it("should validate phone format strictly (09xxxxxxxxx)", () => {
|
||||
const invalidPhoneForm = {
|
||||
title: "خانه",
|
||||
receptorName: "علی رضایی",
|
||||
phone: "02112345678",
|
||||
province: "تهران",
|
||||
city: "تهران",
|
||||
detail: "خیابان آزادی",
|
||||
zipCode: "1234567890",
|
||||
isDefault: false,
|
||||
};
|
||||
|
||||
const errors = validateAddressForm(invalidPhoneForm);
|
||||
expect(errors.phone).toContain("معتبر نیست");
|
||||
});
|
||||
|
||||
it("should validate zip code format strictly (10 digits)", () => {
|
||||
const invalidZipForm = {
|
||||
title: "خانه",
|
||||
receptorName: "علی رضایی",
|
||||
phone: "09123456789",
|
||||
province: "تهران",
|
||||
city: "تهران",
|
||||
detail: "خیابان آزادی",
|
||||
zipCode: "12345", // not 10 digits
|
||||
isDefault: false,
|
||||
};
|
||||
|
||||
const errors = validateAddressForm(invalidZipForm);
|
||||
expect(errors.zipCode).toContain("۱۰ رقم");
|
||||
});
|
||||
|
||||
it("should pass validation with valid data including Persian digits", () => {
|
||||
const validForm = {
|
||||
title: "دفتر",
|
||||
receptorName: "سارا امینی",
|
||||
phone: "۰۹۱۲۳۴۵۶۷۸۹",
|
||||
province: "تهران",
|
||||
city: "تهران",
|
||||
detail: "خیابان انقلاب پلاک ۱۰",
|
||||
zipCode: "۱۲۳۴۵۶۷۸۹۰",
|
||||
isDefault: true,
|
||||
};
|
||||
|
||||
const errors = validateAddressForm(validForm);
|
||||
expect(Object.keys(errors).length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("AddressModal Component Rendering & Form Submission", () => {
|
||||
it("should render modal form when isOpen is true", () => {
|
||||
render(
|
||||
<AddressModal
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
onSave={vi.fn()}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText("افزودن آدرس جدید")).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText("مثال: منزل اصلی")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should populate fields when editing an existing address", async () => {
|
||||
const existingAddress = {
|
||||
id: "addr-1",
|
||||
title: "منزل پدری",
|
||||
receptorName: "رضا محمدی",
|
||||
phone: "09129876543",
|
||||
province: "تهران",
|
||||
city: "تهران",
|
||||
detail: "خیابان بهار کوچه دوم",
|
||||
zipCode: "9876543210",
|
||||
isDefault: true,
|
||||
};
|
||||
|
||||
render(
|
||||
<AddressModal
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
onSave={vi.fn()}
|
||||
editingAddress={existingAddress}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText("ویرایش آدرس ارسال")).toBeInTheDocument();
|
||||
await waitFor(() => {
|
||||
expect(screen.getByDisplayValue("منزل پدری")).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue("رضا محمدی")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import React from 'react';
|
||||
import {render,fireEvent,act,cleanup} from '@testing-library/react';
|
||||
import {vi,beforeEach,afterEach,it,expect} from 'vitest';
|
||||
import AnalyticsDeferred from '../AnalyticsDeferred';
|
||||
beforeEach(()=>{vi.useFakeTimers();document.head.innerHTML='';delete window.dataLayer;delete window.clarity;});
|
||||
afterEach(()=>{cleanup();vi.useRealTimers();vi.unstubAllGlobals();});
|
||||
it('defers tags until interaction and loads only once',()=>{render(<AnalyticsDeferred gtmId="GTM-test" gaId="G-test" clarityId="test"/>);expect(document.scripts).toHaveLength(0);fireEvent.scroll(window);fireEvent.keyDown(window);act(()=>vi.advanceTimersByTime(3500));expect(document.scripts).toHaveLength(3);expect(window.dataLayer).toEqual(expect.arrayContaining([['config','G-test',{page_path:'/'}]]));});
|
||||
it.each(['scroll','touchstart','mousemove','keydown'])('loads on %s',event=>{render(<AnalyticsDeferred gtmId="GTM-test"/>);fireEvent(window,new Event(event));expect(document.scripts).toHaveLength(1);});
|
||||
it('loads clarity when no script exists',()=>{render(<AnalyticsDeferred clarityId="solo"/>);fireEvent.scroll(window);expect(document.querySelector('script')?.src).toBe('https://www.clarity.ms/tag/solo');});
|
||||
it('preserves the existing clarity implementation',()=>{const clarity=vi.fn();window.clarity=clarity;render(<AnalyticsDeferred clarityId="existing"/>);fireEvent.scroll(window);expect(window.clarity).toBe(clarity);expect(document.querySelector('script')?.src).toBe('https://www.clarity.ms/tag/existing');});
|
||||
it('queues clarity calls before its script initializes',()=>{render(<AnalyticsDeferred clarityId="queued"/>);fireEvent.scroll(window);window.clarity('event','checkout');expect(window.clarity.q).toEqual([['event','checkout']]);});
|
||||
it('falls back after 3500ms and reuses existing GA script',()=>{const s=document.createElement('script');s.src='https://www.googletagmanager.com/gtag/js?id=G-test';document.head.append(s);render(<AnalyticsDeferred gaId="G-test"/>);act(()=>vi.advanceTimersByTime(3499));expect(window.dataLayer).toBeUndefined();act(()=>vi.advanceTimersByTime(1));expect(document.scripts).toHaveLength(1);});
|
||||
it('cancels idle work on unmount',()=>{let cb:()=>void=()=>{};vi.stubGlobal('requestIdleCallback',vi.fn(fn=>{cb=fn;return 9;}));vi.stubGlobal('cancelIdleCallback',vi.fn());const v=render(<AnalyticsDeferred gtmId="GTM-test"/>);act(()=>vi.advanceTimersByTime(3500));v.unmount();act(()=>cb());expect(document.scripts).toHaveLength(0);expect(cancelIdleCallback).toHaveBeenCalledWith(9);});
|
||||
it('unmount removes event and timeout callbacks',()=>{const v=render(<AnalyticsDeferred gtmId="GTM-test"/>);v.unmount();fireEvent.scroll(window);act(()=>vi.advanceTimersByTime(4000));expect(document.scripts).toHaveLength(0);});
|
||||
@@ -0,0 +1,256 @@
|
||||
"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 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: ["بیاشتهایی"],
|
||||
},
|
||||
];
|
||||
|
||||
describe("ArchivePage Component", () => {
|
||||
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("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");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,274 @@
|
||||
"use client";
|
||||
import React from "react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import AuthModal from "../AuthModal";
|
||||
import { authService } from "../../lib/services/authService";
|
||||
import { useUserStore } from "../../lib/store/userStore";
|
||||
import { useSettingsStore } from "../../lib/store/settingsStore";
|
||||
import { toast } from "sonner";
|
||||
|
||||
vi.mock("../../lib/services/authService", () => ({
|
||||
authService: {
|
||||
sendOtp: vi.fn(),
|
||||
verifyOtp: vi.fn(),
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/store/userStore", () => ({
|
||||
useUserStore: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/store/settingsStore", () => ({
|
||||
useSettingsStore: vi.fn((selector) => {
|
||||
const state = {
|
||||
getText: (_k: string, def: string) => def,
|
||||
getBoolean: (_k: string, def: boolean = true) => def,
|
||||
};
|
||||
if (typeof selector === "function") {
|
||||
return selector(state);
|
||||
}
|
||||
return state;
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("sonner", () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock OtpInput5
|
||||
vi.mock("../OtpInput5", () => ({
|
||||
default: ({
|
||||
value,
|
||||
onChange,
|
||||
onComplete,
|
||||
disabled,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (val: string) => void;
|
||||
onComplete?: (code: string) => void;
|
||||
disabled?: boolean;
|
||||
}) => (
|
||||
<div data-testid="otp-input-container">
|
||||
<input
|
||||
data-testid="mock-otp-input"
|
||||
type="text"
|
||||
maxLength={5}
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
onChange(val);
|
||||
if (val.length === 5 && onComplete) {
|
||||
onComplete(val);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
describe("AuthModal Component", () => {
|
||||
const mockOnClose = vi.fn();
|
||||
const mockFetchProfile = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
vi.mocked(useUserStore).mockReturnValue({
|
||||
fetchProfile: mockFetchProfile,
|
||||
isLoggedIn: false,
|
||||
} as any);
|
||||
});
|
||||
|
||||
it("does not render when isOpen is false", () => {
|
||||
const { container } = render(<AuthModal isOpen={false} onClose={mockOnClose} />);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it("renders modal heading and login OTP view when isOpen is true", () => {
|
||||
render(<AuthModal isOpen={true} onClose={mockOnClose} />);
|
||||
|
||||
expect(screen.getByText("احراز هویت کنینا")).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText("۰۹۱۲۳۴۵۶۷۸۹")).toBeInTheDocument();
|
||||
expect(screen.getByText("دریافت کد تایید و ورود")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("calls onClose when clicking close button or backdrop", () => {
|
||||
const { container } = render(<AuthModal isOpen={true} onClose={mockOnClose} />);
|
||||
|
||||
// Click backdrop
|
||||
const backdrop = container.querySelector(".fixed.inset-0.bg-medical-gray-900\\/60");
|
||||
if (backdrop) {
|
||||
fireEvent.click(backdrop);
|
||||
expect(mockOnClose).toHaveBeenCalled();
|
||||
}
|
||||
|
||||
mockOnClose.mockClear();
|
||||
|
||||
// Click close button (the round close button at header)
|
||||
const closeBtn = container.querySelector("button.rounded-full");
|
||||
expect(closeBtn).toBeInTheDocument();
|
||||
if (closeBtn) {
|
||||
fireEvent.click(closeBtn);
|
||||
expect(mockOnClose).toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
|
||||
it("validates mobile number on OTP request submission", async () => {
|
||||
render(<AuthModal isOpen={true} onClose={mockOnClose} />);
|
||||
|
||||
const phoneInput = screen.getByPlaceholderText("۰۹۱۲۳۴۵۶۷۸۹");
|
||||
// Enter invalid number
|
||||
fireEvent.change(phoneInput, { target: { value: "0912123" } });
|
||||
|
||||
// Try submitting
|
||||
const submitBtn = screen.getByText("دریافت کد تایید و ورود").closest("button");
|
||||
expect(submitBtn).toBeDisabled();
|
||||
});
|
||||
|
||||
it("sends OTP and navigates to OTP verification step on valid phone submission", async () => {
|
||||
vi.mocked(authService.sendOtp).mockResolvedValue({ success: true } as any);
|
||||
|
||||
render(<AuthModal isOpen={true} onClose={mockOnClose} />);
|
||||
|
||||
const phoneInput = screen.getByPlaceholderText("۰۹۱۲۳۴۵۶۷۸۹");
|
||||
fireEvent.change(phoneInput, { target: { value: "09123456789" } });
|
||||
|
||||
const submitBtn = screen.getByText("دریافت کد تایید و ورود").closest("button")!;
|
||||
expect(submitBtn).not.toBeDisabled();
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(authService.sendOtp).toHaveBeenCalledWith("09123456789");
|
||||
expect(toast.success).toHaveBeenCalledWith("کد تایید با موفقیت پیامک شد");
|
||||
});
|
||||
|
||||
// Subview changed to otp-verify
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("تایید شماره تلفن")).toBeInTheDocument();
|
||||
expect(screen.getByTestId("mock-otp-input")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("allows navigating back to phone edit from OTP step", async () => {
|
||||
vi.mocked(authService.sendOtp).mockResolvedValue({ success: true } as any);
|
||||
|
||||
render(<AuthModal isOpen={true} onClose={mockOnClose} />);
|
||||
|
||||
const phoneInput = screen.getByPlaceholderText("۰۹۱۲۳۴۵۶۷۸۹");
|
||||
fireEvent.change(phoneInput, { target: { value: "09123456789" } });
|
||||
fireEvent.click(screen.getByText("دریافت کد تایید و ورود").closest("button")!);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("تایید شماره تلفن")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Click back button inside OTP view
|
||||
const backBtn = screen.getByText("تایید شماره تلفن").previousSibling as HTMLElement;
|
||||
fireEvent.click(backBtn);
|
||||
|
||||
// Should return to main login view
|
||||
await waitFor(() => {
|
||||
expect(screen.getByPlaceholderText("۰۹۱۲۳۴۵۶۷۸۹")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("verifies OTP and completes login on 5-digit code entry", async () => {
|
||||
vi.mocked(authService.sendOtp).mockResolvedValue({ success: true } as any);
|
||||
vi.mocked(authService.verifyOtp).mockResolvedValue({ success: true, token: "jwt-123" } as any);
|
||||
|
||||
render(<AuthModal isOpen={true} onClose={mockOnClose} />);
|
||||
|
||||
// Step 1: Request OTP
|
||||
const phoneInput = screen.getByPlaceholderText("۰۹۱۲۳۴۵۶۷۸۹");
|
||||
fireEvent.change(phoneInput, { target: { value: "09123456789" } });
|
||||
fireEvent.click(screen.getByText("دریافت کد تایید و ورود").closest("button")!);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("mock-otp-input")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Step 2: Enter 5 digit code
|
||||
const otpInput = screen.getByTestId("mock-otp-input");
|
||||
fireEvent.change(otpInput, { target: { value: "12345" } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(authService.verifyOtp).toHaveBeenCalledWith("09123456789", "12345");
|
||||
expect(mockFetchProfile).toHaveBeenCalled();
|
||||
expect(toast.success).toHaveBeenCalledWith("ورود با موفقیت انجام شد");
|
||||
expect(mockOnClose).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps phone entry retryable after OTP delivery fails", async () => {
|
||||
vi.mocked(authService.sendOtp).mockRejectedValueOnce(new Error('SMS unavailable'));
|
||||
render(<AuthModal isOpen={true} onClose={mockOnClose} />);
|
||||
fireEvent.change(screen.getByPlaceholderText('۰۹۱۲۳۴۵۶۷۸۹'), { target: { value: '09128887766' } });
|
||||
fireEvent.click(screen.getByText('دریافت کد تایید و ورود'));
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('SMS unavailable'));
|
||||
expect(screen.queryByTestId('mock-otp-input')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('دریافت کد تایید و ورود').closest('button')).not.toBeDisabled();
|
||||
expect(mockFetchProfile).not.toHaveBeenCalled();
|
||||
expect(mockOnClose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("allows corrected OTP after verification rejection", async () => {
|
||||
vi.mocked(authService.sendOtp).mockResolvedValueOnce({ success: true } as never);
|
||||
vi.mocked(authService.verifyOtp).mockRejectedValueOnce(new Error('Invalid code')).mockResolvedValueOnce({ success: true } as never);
|
||||
render(<AuthModal isOpen={true} onClose={mockOnClose} />);
|
||||
fireEvent.change(screen.getByPlaceholderText('۰۹۱۲۳۴۵۶۷۸۹'), { target: { value: '09127776655' } });
|
||||
fireEvent.click(screen.getByText('دریافت کد تایید و ورود'));
|
||||
const input = await screen.findByTestId('mock-otp-input');
|
||||
fireEvent.change(input, { target: { value: '00000' } });
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Invalid code'));
|
||||
expect(mockOnClose).not.toHaveBeenCalled();
|
||||
expect(mockFetchProfile).not.toHaveBeenCalled();
|
||||
expect(input).not.toBeDisabled();
|
||||
fireEvent.change(input, { target: { value: '54321' } });
|
||||
await waitFor(() => expect(mockOnClose).toHaveBeenCalledTimes(1));
|
||||
expect(authService.verifyOtp).toHaveBeenLastCalledWith('09127776655', '54321');
|
||||
});
|
||||
|
||||
it("handles countdown timer and displays remaining cooldown seconds", async () => {
|
||||
vi.mocked(authService.sendOtp).mockResolvedValue({ success: true } as any);
|
||||
|
||||
render(<AuthModal isOpen={true} onClose={mockOnClose} />);
|
||||
|
||||
const phoneInput = screen.getByPlaceholderText("۰۹۱۲۳۴۵۶۷۸۹");
|
||||
fireEvent.change(phoneInput, { target: { value: "09120000001" } });
|
||||
const btn = screen.getByText("دریافت کد تایید و ورود").closest("button")!;
|
||||
fireEvent.click(btn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/امکان ارسال مجدد کد تا/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("supports switching between Login and Register tabs", async () => {
|
||||
render(<AuthModal isOpen={true} onClose={mockOnClose} />);
|
||||
|
||||
// Switch to Register tab
|
||||
const registerTab = screen.getByText("ثبتنام کاربر جدید");
|
||||
fireEvent.click(registerTab);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByPlaceholderText("نام...")).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText("نام خانوادگی...")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Switch back to Login tab
|
||||
const loginTab = screen.getByText("ورود به حساب");
|
||||
fireEvent.click(loginTab);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("دریافت کد تایید و ورود")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,154 @@
|
||||
import React from "react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import B2BLandingClient from "../B2BLandingClient";
|
||||
import api from "../../lib/services/api";
|
||||
import { toast } from "sonner";
|
||||
|
||||
// Mock api
|
||||
vi.mock("../../lib/services/api", () => ({
|
||||
default: {
|
||||
post: vi.fn(),
|
||||
get: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock sonner toast
|
||||
vi.mock("sonner", () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock settingsStore
|
||||
vi.mock("../../lib/store/settingsStore", () => ({
|
||||
useSettingsStore: (selector: any) =>
|
||||
selector({
|
||||
getText: (key: string, fallback: string) => {
|
||||
if (key === "contact_phone") return "۰۹۲۱۱۲۳۱۵۱۷";
|
||||
if (key === "B2B_DISCOUNT_PERCENT") return "۳۵";
|
||||
return fallback;
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
describe("B2BLandingClient Component", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("renders B2B hero section, partner benefits, and contact phone", () => {
|
||||
render(<B2BLandingClient />);
|
||||
|
||||
expect(screen.getByText(/تأمین عمده و همکاری تجاری مکملهای/)).toBeInTheDocument();
|
||||
expect(screen.getByText("کنینا آلمان")).toBeInTheDocument();
|
||||
expect(screen.getByText(/پرتال رسمی همکاران تجاری، کلینیکها و پتشاپها/)).toBeInTheDocument();
|
||||
expect(screen.getByText("تا ۳۵٪ تخفیف")).toBeInTheDocument();
|
||||
expect(screen.getAllByText("۰۹۲۱۱۲۳۱۵۱۷").length).toBeGreaterThan(0);
|
||||
expect(screen.getByText("چرا کلینیکها و پتشاپها کنینا را انتخاب میکنند؟")).toBeInTheDocument();
|
||||
expect(screen.getByText("اصالت قطعی آلمان")).toBeInTheDocument();
|
||||
expect(screen.getByText("حاشیه سود رقابتی")).toBeInTheDocument();
|
||||
expect(screen.getByText("ارسال سریع و مطمئن")).toBeInTheDocument();
|
||||
expect(screen.getByText("پشتیبانی علمی و بالینی")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("toggles FAQ accordion items when clicked", () => {
|
||||
render(<B2BLandingClient />);
|
||||
|
||||
const faqQuestion = screen.getByText("حداقل مبلغ و تعداد برای سفارش عمده B2B چقدر است؟");
|
||||
expect(faqQuestion).toBeInTheDocument();
|
||||
|
||||
// Answer should not be visible initially
|
||||
expect(
|
||||
screen.queryByText(/برای اولین سفارش همکاران گرامی، حداقل سبد خرید با تخفیف همکار معادل ۵ میلیون تومان تعریف شده/)
|
||||
).not.toBeInTheDocument();
|
||||
|
||||
// Click question button
|
||||
fireEvent.click(faqQuestion);
|
||||
expect(
|
||||
screen.getByText(/برای اولین سفارش همکاران گرامی، حداقل سبد خرید با تخفیف همکار معادل ۵ میلیون تومان تعریف شده/)
|
||||
).toBeInTheDocument();
|
||||
|
||||
// Click again to close
|
||||
fireEvent.click(faqQuestion);
|
||||
expect(
|
||||
screen.queryByText(/برای اولین سفارش همکاران گرامی، حداقل سبد خرید با تخفیف همکار معادل ۵ میلیون تومان تعریف شده/)
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("validates required fields and shows toast error when businessName or phone is missing", async () => {
|
||||
const { container } = render(<B2BLandingClient />);
|
||||
|
||||
const form = container.querySelector("form");
|
||||
expect(form).not.toBeNull();
|
||||
fireEvent.submit(form!);
|
||||
|
||||
expect(toast.error).toHaveBeenCalledWith("لطفاً نام مجموعه و شماره تماس را وارد کنید.");
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("submits B2B inquiry form successfully and displays confirmation view", async () => {
|
||||
vi.mocked(api.post).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
render(<B2BLandingClient />);
|
||||
|
||||
const businessNameInput = screen.getByPlaceholderText("مثلاً کلینیک تخصصی دکتر البرزی");
|
||||
const businessTypeSelect = screen.getByRole("combobox");
|
||||
const contactNameInput = screen.getByPlaceholderText("نام و نام خانوادگی");
|
||||
const phoneInput = screen.getByPlaceholderText("۰۹۱۲۳۴۵۶۷۸۹");
|
||||
const cityInput = screen.getByPlaceholderText("مثلاً تهران / اصفهان");
|
||||
const notesInput = screen.getByPlaceholderText(
|
||||
"در صورت داشتن نیاز دارویی خاص یا حجم تخمینی سفارش، در اینجا درج فرمایید..."
|
||||
);
|
||||
|
||||
fireEvent.change(businessNameInput, { target: { value: "کلینیک تخصصی آریا" } });
|
||||
fireEvent.change(businessTypeSelect, { target: { value: "بیمارستان دامپزشکی" } });
|
||||
fireEvent.change(contactNameInput, { target: { value: "دکتر حسینی" } });
|
||||
fireEvent.change(phoneInput, { target: { value: "09121112233" } });
|
||||
fireEvent.change(cityInput, { target: { value: "تهران" } });
|
||||
fireEvent.change(notesInput, { target: { value: "سفارش اولیه مکملهای حرکتی و کلسیم" } });
|
||||
|
||||
const submitBtn = screen.getByRole("button", { name: /ثبت درخواست و فعالسازی حساب همکار/i });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith("/wholesale/apply", {
|
||||
businessName: "کلینیک تخصصی آریا (بیمارستان دامپزشکی - تهران) - رابط: دکتر حسینی",
|
||||
licenseNumber: "09121112233",
|
||||
notes: "سفارش اولیه مکملهای حرکتی و کلسیم",
|
||||
});
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(toast.success).toHaveBeenCalledWith(
|
||||
expect.stringContaining("درخواست همکاری شما با موفقیت ثبت شد")
|
||||
);
|
||||
expect(screen.getByText("درخواست شما با موفقیت ثبت شد")).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText(/کارشناسان فروش سازمانی کنینا ایران جهت احراز هویت/)
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("handles submission failure and shows error toast", async () => {
|
||||
vi.mocked(api.post).mockRejectedValueOnce(new Error("Server error"));
|
||||
|
||||
render(<B2BLandingClient />);
|
||||
|
||||
const businessNameInput = screen.getByPlaceholderText("مثلاً کلینیک تخصصی دکتر البرزی");
|
||||
const phoneInput = screen.getByPlaceholderText("۰۹۱۲۳۴۵۶۷۸۹");
|
||||
|
||||
fireEvent.change(businessNameInput, { target: { value: "پتشاپ امید" } });
|
||||
fireEvent.change(phoneInput, { target: { value: "09351234567" } });
|
||||
|
||||
const submitBtn = screen.getByRole("button", { name: /ثبت درخواست و فعالسازی حساب همکار/i });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(toast.error).toHaveBeenCalledWith(
|
||||
"خطایی در ثبت درخواست رخ داد. لطفاً با پشتیبانی تماس بگیرید."
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import React from 'react';
|
||||
import {render,screen,fireEvent,waitFor,cleanup,act} from '@testing-library/react';
|
||||
import {vi,beforeEach,afterEach,it,expect} from 'vitest';
|
||||
import B2BPortal from '../B2BPortal';
|
||||
const state=vi.hoisted(()=>({role:'User_Wholesale',addItem:vi.fn(),getProducts:vi.fn(),post:vi.fn(),success:vi.fn(),error:vi.fn()}));
|
||||
vi.mock('../../lib/store/cartStore',()=>({useCartStore:()=>({addItem:state.addItem})}));
|
||||
vi.mock('../../lib/store/userStore',()=>({useUserStore:()=>({role:state.role})}));
|
||||
vi.mock('../../lib/store/settingsStore',()=>({useSettingsStore:{getState:()=>({getText:()=> '20'})}}));
|
||||
vi.mock('../../lib/services/productService',()=>({productService:{getProducts:state.getProducts}}));
|
||||
vi.mock('../../lib/services/api',()=>({default:{post:state.post}}));
|
||||
vi.mock('sonner',()=>({toast:{success:state.success,error:state.error}}));
|
||||
vi.mock('motion/react',()=>({AnimatePresence:({children}:{children:React.ReactNode})=><>{children}</>,motion:{div:({children,className}:{children:React.ReactNode;className:string})=><div className={className}>{children}</div>}}));
|
||||
vi.mock('../SafeImage',()=>({default:({alt}:{alt:string})=><img alt={alt}/>}));
|
||||
const products=[{id:'1',name:'Joint care',artNo:'A1',priceValue:1000,wholesalePrice:650,category:'joints'},{id:'2',name:'Skin care',artNo:'B2',priceValue:2000,category:'skin'}];
|
||||
beforeEach(()=>{vi.clearAllMocks();state.role='User_Wholesale';state.getProducts.mockResolvedValue({data:products});state.post.mockResolvedValue({});});
|
||||
afterEach(()=>{cleanup();vi.restoreAllMocks();});
|
||||
it('uses specific price and settings discount fallback',async()=>{render(<B2BPortal onClose={()=>{}}/>);await screen.findByText('Joint care');expect(state.getProducts).toHaveBeenCalledWith({limit:999});expect(screen.getByText('۶۵۰ تومان')).toBeInTheDocument();expect(screen.getByText('۱,۶۰۰ تومان')).toBeInTheDocument();});
|
||||
it.each(['User_Wholesale','ADMIN','User_Partner'])('unlocks wholesale prices for %s',async role=>{state.role=role;render(<B2BPortal onClose={()=>{}}/>);await screen.findByText('Joint care');expect(screen.queryByText('نیازمند تایید ادمین')).not.toBeInTheDocument();});
|
||||
it('hides wholesale prices for unverified users',async()=>{state.role='USER';render(<B2BPortal onClose={()=>{}}/>);await screen.findByText('Joint care');expect(screen.getAllByText('نیازمند تایید ادمین')).toHaveLength(2);expect(screen.queryByText('۶۵۰ تومان')).not.toBeInTheDocument();});
|
||||
it('filters by code preserving selection and clamps negative quantity',async()=>{render(<B2BPortal onClose={()=>{}}/>);await screen.findByText('Joint care');expect(screen.getByRole('button',{name:/افزودن کلی/})).toBeDisabled();fireEvent.change(screen.getAllByRole('spinbutton')[0],{target:{value:'3'}});fireEvent.change(screen.getAllByRole('spinbutton')[1],{target:{value:'-2'}});fireEvent.change(screen.getByPlaceholderText('جستجوی کد کالا یا نام محصول...'),{target:{value:'B2'}});expect(screen.queryByText('Joint care')).not.toBeInTheDocument();fireEvent.click(screen.getByRole('button',{name:/افزودن کلی/}));expect(state.addItem).toHaveBeenCalledExactlyOnceWith(products[0],3);expect(screen.getByText(/سفارشات با موفقیت/)).toBeInTheDocument();});
|
||||
it.each([false,true])('consultation success/error: failure=%s',async failure=>{state.role='USER';if(failure)state.post.mockRejectedValue(new Error('offline'));const {container}=render(<B2BPortal onClose={()=>{}}/>);fireEvent.change(screen.getByPlaceholderText('نام مجموعه / کلینیک / داروخانه'),{target:{value:'Clinic'}});fireEvent.change(screen.getByPlaceholderText('شماره تماس همراه'),{target:{value:'09120000000'}});fireEvent.submit(container.querySelector('form')!);await waitFor(()=>expect(failure?state.error:state.success).toHaveBeenCalledOnce());expect(state.post).toHaveBeenCalledWith('/wholesale/apply',{businessName:'Clinic',licenseNumber:'09120000000'});expect(screen.getByPlaceholderText('نام مجموعه / کلینیک / داروخانه')).toHaveValue(failure?'Clinic':'');});
|
||||
it('handles product loading failure visibly',async()=>{state.getProducts.mockRejectedValueOnce(new Error('offline'));render(<B2BPortal onClose={()=>{}}/>);expect(await screen.findByText(/خطا در دریافت محصولات/)).toBeInTheDocument();expect(screen.getByRole('button',{name:/افزودن کلی/})).toBeDisabled();});
|
||||
it.each([false,true])('ignores a settled request after unmount: failure=%s',async failure=>{let resolve!:(value:{data:typeof products})=>void;let reject!:(reason:Error)=>void;state.getProducts.mockReturnValueOnce(new Promise((yes,no)=>{resolve=yes;reject=no;}));const first=render(<B2BPortal onClose={()=>{}}/>);first.unmount();const next=render(<B2BPortal onClose={()=>{}}/>);await screen.findByText('Joint care');await act(async()=>{if(failure)reject(new Error('late failure'));else resolve({data:[{...products[0],name:'Stale product'}]});});expect(screen.queryByRole('alert')).not.toBeInTheDocument();expect(screen.queryByText('Stale product')).not.toBeInTheDocument();expect(screen.getByText('Joint care')).toBeInTheDocument();next.unmount();});
|
||||
it('closes via callback',()=>{const close=vi.fn();const {container}=render(<B2BPortal onClose={close}/>);fireEvent.click(container.querySelector('button')!);expect(close).toHaveBeenCalledOnce();});
|
||||
@@ -0,0 +1,51 @@
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import BackButton from '../BackButton';
|
||||
|
||||
const mockBack = vi.fn();
|
||||
const mockPush = vi.fn();
|
||||
|
||||
vi.mock('next/navigation', () => ({
|
||||
useRouter: () => ({
|
||||
back: mockBack,
|
||||
push: mockPush,
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('BackButton Component', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders with default label', () => {
|
||||
render(<BackButton />);
|
||||
expect(screen.getByText('بازگشت')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders with custom label', () => {
|
||||
render(<BackButton label="بازگشت به فروشگاه" />);
|
||||
expect(screen.getByText('بازگشت به فروشگاه')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls router.back when history length is greater than 1', () => {
|
||||
Object.defineProperty(window, 'history', {
|
||||
value: { length: 3 },
|
||||
writable: true,
|
||||
});
|
||||
render(<BackButton />);
|
||||
const button = screen.getByRole('button');
|
||||
fireEvent.click(button);
|
||||
expect(mockBack).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('navigates to home when history length is 1 or less', () => {
|
||||
Object.defineProperty(window, 'history', {
|
||||
value: { length: 1 },
|
||||
writable: true,
|
||||
});
|
||||
render(<BackButton />);
|
||||
const button = screen.getByRole('button');
|
||||
fireEvent.click(button);
|
||||
expect(mockPush).toHaveBeenCalledWith('/');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
import React from "react";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import BannerPlacement from "../BannerPlacement";
|
||||
import { Banner } from "../../lib/types";
|
||||
|
||||
const mockBanners: Banner[] = [
|
||||
{
|
||||
id: "b1",
|
||||
title: "بنر میانی اول",
|
||||
subtitle: "توضیحات بنر اول",
|
||||
imageUrl: "/images/banner1.jpg",
|
||||
linkUrl: "/shop?category=joints",
|
||||
position: "home_middle",
|
||||
isActive: true,
|
||||
},
|
||||
{
|
||||
id: "b2",
|
||||
title: "بنر میانی دوم خارجی",
|
||||
subtitle: "لینک به سایت دیگر",
|
||||
imageUrl: "/images/banner2.jpg",
|
||||
linkUrl: "https://external.example.com",
|
||||
position: "home_middle",
|
||||
isActive: true,
|
||||
},
|
||||
{
|
||||
id: "b3",
|
||||
title: "بنر غیرفعال",
|
||||
imageUrl: "/images/banner3.jpg",
|
||||
linkUrl: "/shop",
|
||||
position: "home_middle",
|
||||
isActive: false,
|
||||
},
|
||||
{
|
||||
id: "b4",
|
||||
title: "بنر عریض پایین خانه",
|
||||
subtitle: "تخفیف ویژه مکملها",
|
||||
imageUrl: "/images/banner4.jpg",
|
||||
linkUrl: "/shop?sort=discount",
|
||||
position: "home_bottom",
|
||||
isActive: true,
|
||||
},
|
||||
{
|
||||
id: "b5",
|
||||
title: "بنر ستون کناری محصول",
|
||||
imageUrl: "/images/banner5.jpg",
|
||||
position: "product_sidebar",
|
||||
isActive: true,
|
||||
},
|
||||
{
|
||||
id: "b6",
|
||||
title: "بنر بدون عکس",
|
||||
imageUrl: "",
|
||||
position: "home_middle",
|
||||
isActive: true,
|
||||
},
|
||||
];
|
||||
|
||||
describe("BannerPlacement Component", () => {
|
||||
it("renders null when banners array is empty or undefined", () => {
|
||||
const { container: c1 } = render(<BannerPlacement banners={[]} position="home_middle" />);
|
||||
expect(c1.firstChild).toBeNull();
|
||||
|
||||
const { container: c2 } = render(<BannerPlacement banners={null as any} position="home_middle" />);
|
||||
expect(c2.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it("renders null when no banners match the requested position or active state", () => {
|
||||
const { container } = render(<BannerPlacement banners={mockBanners} position="category_top" />);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it("filters out inactive banners and banners without imageUrl", () => {
|
||||
render(<BannerPlacement banners={mockBanners} position="home_middle" />);
|
||||
expect(screen.getByText("بنر میانی اول")).toBeInTheDocument();
|
||||
expect(screen.getByText("توضیحات بنر اول")).toBeInTheDocument();
|
||||
expect(screen.getByText("بنر میانی دوم خارجی")).toBeInTheDocument();
|
||||
expect(screen.queryByText("بنر غیرفعال")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("بنر بدون عکس")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders responsive multi-column layout for home_middle when multiple banners exist", () => {
|
||||
const { container } = render(<BannerPlacement banners={mockBanners} position="home_middle" />);
|
||||
const gridEl = container.querySelector(".grid");
|
||||
expect(gridEl).toBeInTheDocument();
|
||||
expect(gridEl).toHaveClass("md:grid-cols-2");
|
||||
});
|
||||
|
||||
it("renders single column layout for home_middle when only 1 banner exists", () => {
|
||||
const singleBanner = [mockBanners[0]];
|
||||
const { container } = render(<BannerPlacement banners={singleBanner} position="home_middle" />);
|
||||
const gridEl = container.querySelector(".grid");
|
||||
expect(gridEl).toBeInTheDocument();
|
||||
expect(gridEl).toHaveClass("grid-cols-1");
|
||||
expect(gridEl).not.toHaveClass("md:grid-cols-2");
|
||||
});
|
||||
|
||||
it("renders internal links using Next.js Link and external links with target=_blank", () => {
|
||||
render(<BannerPlacement banners={mockBanners} position="home_middle" />);
|
||||
|
||||
// Internal link
|
||||
const internalLink = screen.getByText("بنر میانی اول").closest("a");
|
||||
expect(internalLink).toBeInTheDocument();
|
||||
expect(internalLink).toHaveAttribute("href", "/shop?category=joints");
|
||||
expect(internalLink).not.toHaveAttribute("target", "_blank");
|
||||
|
||||
// External link
|
||||
const externalLink = screen.getByText("بنر میانی دوم خارجی").closest("a");
|
||||
expect(externalLink).toBeInTheDocument();
|
||||
expect(externalLink).toHaveAttribute("href", "https://external.example.com");
|
||||
expect(externalLink).toHaveAttribute("target", "_blank");
|
||||
expect(externalLink).toHaveAttribute("rel", "noopener noreferrer");
|
||||
});
|
||||
|
||||
it("renders wide layout for home_bottom, shop_top, and category_top positions", () => {
|
||||
const { container } = render(<BannerPlacement banners={mockBanners} position="home_bottom" />);
|
||||
expect(screen.getByText("بنر عریض پایین خانه")).toBeInTheDocument();
|
||||
expect(screen.getByText("تخفیف ویژه مکملها")).toBeInTheDocument();
|
||||
const aspectContainer = container.querySelector(".aspect-\\[21\\/6\\]");
|
||||
expect(aspectContainer).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders sidebar layout for product_sidebar position without link when linkUrl is missing", () => {
|
||||
const { container } = render(<BannerPlacement banners={mockBanners} position="product_sidebar" />);
|
||||
const titleEl = screen.getByText("بنر ستون کناری محصول");
|
||||
expect(titleEl).toBeInTheDocument();
|
||||
expect(titleEl.closest("a")).toBeNull();
|
||||
const aspectContainer = container.querySelector(".aspect-\\[4\\/3\\]");
|
||||
expect(aspectContainer).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("applies custom className to the section or container wrapper", () => {
|
||||
const { container } = render(
|
||||
<BannerPlacement banners={mockBanners} position="home_middle" className="custom-banner-class" />
|
||||
);
|
||||
expect(container.firstChild).toHaveClass("custom-banner-class");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import React from 'react';
|
||||
import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react';
|
||||
const h = vi.hoisted(() => ({ push: vi.fn(), back: vi.fn(), replace: vi.fn() }));
|
||||
vi.mock('next/navigation', () => ({ useRouter: () => h, useSearchParams: () => new URLSearchParams(window.location.search) }));
|
||||
vi.mock('motion/react', async () => {
|
||||
const R = await import('react'); const cache: Record<string, React.ComponentType<any>> = {};
|
||||
return { AnimatePresence: ({children}: any) => children, motion: new Proxy({}, { get: (_, tag: string) => cache[tag] ||= R.forwardRef(({children, ...props}: any, ref) => {
|
||||
const clean = Object.fromEntries(Object.entries(props).filter(([k]) => !['initial','animate','exit','transition','whileHover','whileTap','whileInView','viewport','layout','layoutId','drag','dragConstraints','dragElastic','onDragEnd'].includes(k)));
|
||||
return R.createElement(tag, {...clean, ref}, children);
|
||||
}) }) };
|
||||
});
|
||||
vi.mock('next/image', () => ({ default: ({unoptimized, priority, fill, ...props}: any) => <img {...props} /> }));
|
||||
vi.mock('sonner', () => ({ toast: {success: vi.fn(), error: vi.fn(), info: vi.fn()} }));
|
||||
import { toast } from 'sonner';
|
||||
afterEach(cleanup);
|
||||
import BlogPage from '../BlogPage';
|
||||
vi.mock('../../lib/services/productService',()=>({productService:{getProducts:vi.fn().mockResolvedValue({data:[]})}}));
|
||||
const blogs=[{id:'1',slug:'joint',title:'Joint article',excerpt:'Mobility guide',image:'/a.png',date:'2026-01-01',author:'Alpha',content:'Guide',categoryId:'joints',tags:[{id:'t1',name:'health'}]},{id:'2',slug:'skin',title:'Skin article',excerpt:'Coat guide',image:'/b.png',date:'2026-01-02',author:'Beta',content:'Guide',categoryId:'skin',featured:true,tags:[{id:'t2',name:'coat'}]}];
|
||||
const categories=[{id:'joints',name:'Joints',slug:'joints'},{id:'skin',name:'Skin',slug:'skin'}];
|
||||
beforeEach(()=>vi.clearAllMocks());
|
||||
describe('BlogPage',()=>{
|
||||
it('prioritizes featured post and navigates',()=>{render(<BlogPage blogs={blogs} categories={categories}/>);expect(screen.getAllByRole('heading',{level:2})[0]).toHaveTextContent('Skin article');fireEvent.click(screen.getByText('Skin article'));expect(h.push).toHaveBeenCalledWith('/blog/skin');});
|
||||
it('combines category, excerpt search and tags then resets empty intersection',()=>{render(<BlogPage blogs={blogs} categories={categories}/>);fireEvent.click(screen.getByRole('button',{name:'Joints'}));expect(h.replace).toHaveBeenCalledWith('/blog?categoryId=joints',{scroll:false});expect(screen.queryByText('Skin article')).not.toBeInTheDocument();fireEvent.change(screen.getByPlaceholderText('جستجو در موضوعات، بیماریها، ویتامینها...'),{target:{value:'MOBILITY'}});expect(screen.getByText('Joint article')).toBeInTheDocument();fireEvent.click(screen.getByRole('button',{name:'#coat'}));expect(screen.getByText('هیچ مقالهای با معیارهای جستجوی شما یافت نشد.')).toBeInTheDocument();fireEvent.click(screen.getByRole('button',{name:'پاکسازی همه فیلترها'}));expect(screen.getByText('Skin article')).toBeInTheDocument();expect(screen.getByText('Joint article')).toBeInTheDocument();});
|
||||
it('syncs category with route props',()=>{const view=render(<BlogPage blogs={blogs} categories={categories} initialCategoryId="joints"/>);expect(screen.queryByText('Skin article')).not.toBeInTheDocument();view.rerender(<BlogPage blogs={blogs} categories={categories} initialCategoryId="skin"/>);expect(screen.queryByText('Joint article')).not.toBeInTheDocument();});
|
||||
it('clears search and toggles tags off',()=>{render(<BlogPage blogs={blogs}/>);fireEvent.click(screen.getByRole('button',{name:'#health'}));expect(screen.queryByText('Skin article')).not.toBeInTheDocument();fireEvent.click(screen.getByRole('button',{name:'#health'}));expect(screen.getByText('Skin article')).toBeInTheDocument();fireEvent.change(screen.getByPlaceholderText('جستجو در موضوعات، بیماریها، ویتامینها...'),{target:{value:'missing'}});fireEvent.click(screen.getByRole('button',{name:'پاک کردن'}));expect(screen.getByText('Skin article')).toBeInTheDocument();});
|
||||
it('renders empty collection and returns home',()=>{render(<BlogPage blogs={[]}/>);expect(screen.getByText('هیچ مقالهای با معیارهای جستجوی شما یافت نشد.')).toBeInTheDocument();fireEvent.click(screen.getByRole('button',{name:'بازگشت به خانه'}));expect(h.push).toHaveBeenCalledWith('/');});
|
||||
});
|
||||
@@ -0,0 +1,257 @@
|
||||
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}
|
||||
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("registers blog view count on mount via API", async () => {
|
||||
render(
|
||||
<BlogPostClient
|
||||
blog={mockBlog}
|
||||
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}
|
||||
publishedDate="۱۵ فروردین ۱۴۰۵"
|
||||
authorName="دکتر توماس بکر"
|
||||
/>
|
||||
);
|
||||
|
||||
// Related Products
|
||||
expect(screen.getByText("مکملهای مرتبط این مقاله")).toBeInTheDocument();
|
||||
expect(screen.getByText("قرص کانیهیدروکس GAG")).toBeInTheDocument();
|
||||
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("link", { name: /مشاوره هوشمند دارویی/ })).toHaveAttribute(
|
||||
"href",
|
||||
"/smart-advisor"
|
||||
);
|
||||
});
|
||||
|
||||
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}
|
||||
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}
|
||||
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}
|
||||
publishedDate="۱۵ فروردین ۱۴۰۵"
|
||||
authorName="دکتر توماس بکر"
|
||||
/>
|
||||
);
|
||||
|
||||
const shareBtn = screen.getByRole("button", { name: /اشتراکگذاری/ });
|
||||
fireEvent.click(shareBtn);
|
||||
|
||||
expect(writeTextMock).toHaveBeenCalled();
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("لینک کپی شد!")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
"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();
|
||||
|
||||
// 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("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();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import BrandLogo from '../BrandLogo';
|
||||
|
||||
describe('BrandLogo Component', () => {
|
||||
it('renders default text logo with brand name and subtitle', () => {
|
||||
render(<BrandLogo />);
|
||||
expect(screen.getByText('Canina')).toBeInTheDocument();
|
||||
expect(screen.getByText('ایران')).toBeInTheDocument();
|
||||
expect(screen.getByText('نماینده رسمی CANINA PHARMA GMBH GERMANY')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders wrapped with Link to given href', () => {
|
||||
const { container } = render(<BrandLogo href="/custom-url" />);
|
||||
const link = container.querySelector('a');
|
||||
expect(link).toBeInTheDocument();
|
||||
expect(link?.getAttribute('href')).toBe('/custom-url');
|
||||
});
|
||||
|
||||
it('renders without link when href is empty string', () => {
|
||||
const { container } = render(<BrandLogo href="" />);
|
||||
const link = container.querySelector('a');
|
||||
expect(link).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,29 @@
|
||||
"use client";
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import React from 'react';
|
||||
import CartDrawer from '../CartDrawer';
|
||||
import { useCartStore } from '../../lib/store/cartStore';
|
||||
import { useUserStore } from '../../lib/store/userStore';
|
||||
import { useSettingsStore } from '../../lib/store/settingsStore';
|
||||
import { useCatalogMode } from '../../lib/useCatalogMode';
|
||||
import { productService } from '../../lib/services/productService';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
vi.mock('../../lib/store/cartStore', () => ({
|
||||
useCartStore: vi.fn(),
|
||||
useCartStore: Object.assign(vi.fn(), {
|
||||
getState: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('../../lib/store/userStore', () => ({
|
||||
useUserStore: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../lib/store/settingsStore', () => ({
|
||||
useSettingsStore: Object.assign(vi.fn(), {
|
||||
getState: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('../../lib/services/productService', () => ({
|
||||
@@ -17,30 +33,106 @@ vi.mock('../../lib/services/productService', () => ({
|
||||
}));
|
||||
|
||||
vi.mock('../../lib/useCatalogMode', () => ({
|
||||
useCatalogMode: vi.fn(() => ({
|
||||
isCatalogOnly: false,
|
||||
showPrices: true,
|
||||
allowCart: true,
|
||||
allowCheckout: true,
|
||||
showPreorderBtn: false,
|
||||
})),
|
||||
useCatalogMode: vi.fn(),
|
||||
}));
|
||||
|
||||
import { useCatalogMode } from '../../lib/useCatalogMode';
|
||||
vi.mock('sonner', () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock child modals to keep unit tests isolated and fast
|
||||
vi.mock('../AuthModal', () => ({
|
||||
default: ({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) =>
|
||||
isOpen ? <div data-testid="auth-modal"><button onClick={onClose}>Close Auth</button></div> : null,
|
||||
}));
|
||||
|
||||
vi.mock('../DeleteConfirmModal', () => ({
|
||||
default: ({
|
||||
isOpen,
|
||||
onClose,
|
||||
onConfirm,
|
||||
title,
|
||||
message,
|
||||
}: {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onConfirm: () => void;
|
||||
title: string;
|
||||
message: string;
|
||||
}) =>
|
||||
isOpen ? (
|
||||
<div data-testid="delete-confirm-modal">
|
||||
<span>{title}</span>
|
||||
<p>{message}</p>
|
||||
<button onClick={onConfirm}>Confirm Delete</button>
|
||||
<button onClick={onClose}>Cancel Delete</button>
|
||||
</div>
|
||||
) : null,
|
||||
}));
|
||||
|
||||
const mockProduct = {
|
||||
id: 'canhydrox-gag',
|
||||
name: 'Canhydrox GAG',
|
||||
nameFa: 'کانهیدروکس گگ',
|
||||
price: '۱,۰۰۰ تومان',
|
||||
priceValue: 1000,
|
||||
category: 'joints',
|
||||
image: '',
|
||||
image: '/images/canhydrox.png',
|
||||
};
|
||||
|
||||
describe('CartDrawer', () => {
|
||||
const mockSuggestedProduct = {
|
||||
id: 'lachs-ol',
|
||||
name: 'Lachs-Öl',
|
||||
nameFa: 'روغن سالمون خالص',
|
||||
price: '۵۰۰ تومان',
|
||||
priceValue: 500,
|
||||
category: 'skin-coat',
|
||||
image: '/images/lachs.png',
|
||||
};
|
||||
|
||||
describe('CartDrawer - Extended Interactive Test Suite', () => {
|
||||
const mockUpdateQuantity = vi.fn();
|
||||
const mockRemoveItem = vi.fn();
|
||||
const mockToggleSubscription = vi.fn();
|
||||
const mockApplyCoupon = vi.fn();
|
||||
const mockRemoveCoupon = vi.fn();
|
||||
const mockAddItem = vi.fn();
|
||||
const mockOnClose = vi.fn();
|
||||
const mockOnCheckout = vi.fn();
|
||||
const mockOnShopNavigate = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(productService.getProducts).mockResolvedValue({ data: [], total: 0 });
|
||||
|
||||
vi.mocked(productService.getProducts).mockResolvedValue({
|
||||
data: [mockSuggestedProduct as any],
|
||||
total: 1,
|
||||
});
|
||||
|
||||
vi.mocked(useUserStore).mockReturnValue({
|
||||
isLoggedIn: true,
|
||||
profile: { mobile: '09121234567', firstName: 'تست' },
|
||||
} as any);
|
||||
|
||||
const mockGetText = vi.fn((key: string, def?: string) => {
|
||||
if (key === 'REFILL_SUBSCRIPTION_ENABLED') return 'true';
|
||||
if (key === 'REFILL_REWARD_PERCENT') return '5';
|
||||
if (key === 'contact_phone') return '۰۲۱-۸۸۸۸۴۴۴۴';
|
||||
if (key === 'contact_phone_link') return 'tel:02188884444';
|
||||
return def || '';
|
||||
});
|
||||
|
||||
vi.mocked(useSettingsStore).mockImplementation((selector: any) => {
|
||||
return selector({ getText: mockGetText });
|
||||
});
|
||||
(useSettingsStore as any).getState = vi.fn(() => ({
|
||||
getText: mockGetText,
|
||||
}));
|
||||
|
||||
vi.mocked(useCatalogMode).mockReturnValue({
|
||||
isCatalogOnly: false,
|
||||
showPrices: true,
|
||||
@@ -53,66 +145,65 @@ describe('CartDrawer', () => {
|
||||
orderDisabledTitle: '',
|
||||
orderDisabledMessage: '',
|
||||
});
|
||||
|
||||
vi.mocked(useCartStore).mockReturnValue({
|
||||
items: [{ product: mockProduct as any, quantity: 2 }],
|
||||
updateQuantity: mockUpdateQuantity,
|
||||
removeItem: mockRemoveItem,
|
||||
isSubscribed: false,
|
||||
toggleSubscription: mockToggleSubscription,
|
||||
getTotal: () => 2000,
|
||||
getSubtotal: () => 2000,
|
||||
getDiscount: () => 0,
|
||||
coupon: null,
|
||||
applyCoupon: mockApplyCoupon,
|
||||
addItem: mockAddItem,
|
||||
} as any);
|
||||
|
||||
(useCartStore as any).getState = vi.fn(() => ({
|
||||
removeCoupon: mockRemoveCoupon,
|
||||
}));
|
||||
});
|
||||
|
||||
it('renders empty cart state when no items in cart', () => {
|
||||
it('renders empty cart view and calls navigation on button click', () => {
|
||||
vi.mocked(useCartStore).mockReturnValue({
|
||||
items: [],
|
||||
updateQuantity: vi.fn(),
|
||||
removeItem: vi.fn(),
|
||||
updateQuantity: mockUpdateQuantity,
|
||||
removeItem: mockRemoveItem,
|
||||
isSubscribed: false,
|
||||
toggleSubscription: vi.fn(),
|
||||
toggleSubscription: mockToggleSubscription,
|
||||
getTotal: () => 0,
|
||||
getSubtotal: () => 0,
|
||||
getDiscount: () => 0,
|
||||
coupon: null,
|
||||
applyCoupon: vi.fn(),
|
||||
addItem: vi.fn(),
|
||||
} as unknown as ReturnType<typeof useCartStore>);
|
||||
applyCoupon: mockApplyCoupon,
|
||||
addItem: mockAddItem,
|
||||
} as any);
|
||||
|
||||
render(<CartDrawer isOpen={true} onClose={vi.fn()} onCheckout={vi.fn()} />);
|
||||
render(
|
||||
<CartDrawer
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onCheckout={mockOnCheckout}
|
||||
onShopNavigate={mockOnShopNavigate}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('سبد خرید شما خالی است')).toBeInTheDocument();
|
||||
const shopBtn = screen.getByText('مشاهده محصولات تخصصی');
|
||||
fireEvent.click(shopBtn);
|
||||
expect(mockOnClose).toHaveBeenCalled();
|
||||
expect(mockOnShopNavigate).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('renders cart items and total when items are present', () => {
|
||||
vi.mocked(useCartStore).mockReturnValue({
|
||||
items: [{ product: mockProduct, quantity: 2 }],
|
||||
updateQuantity: vi.fn(),
|
||||
removeItem: vi.fn(),
|
||||
isSubscribed: false,
|
||||
toggleSubscription: vi.fn(),
|
||||
getTotal: () => 2000,
|
||||
getSubtotal: () => 2000,
|
||||
getDiscount: () => 0,
|
||||
coupon: null,
|
||||
applyCoupon: vi.fn(),
|
||||
addItem: vi.fn(),
|
||||
} as unknown as ReturnType<typeof useCartStore>);
|
||||
|
||||
render(<CartDrawer isOpen={true} onClose={vi.fn()} onCheckout={vi.fn()} />);
|
||||
|
||||
expect(screen.getByText('Canhydrox GAG')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('۲,۰۰۰').length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('triggers updateQuantity when plus/minus buttons are clicked', () => {
|
||||
const mockUpdateQuantity = vi.fn();
|
||||
vi.mocked(useCartStore).mockReturnValue({
|
||||
items: [{ product: mockProduct, quantity: 2 }],
|
||||
updateQuantity: mockUpdateQuantity,
|
||||
removeItem: vi.fn(),
|
||||
isSubscribed: false,
|
||||
toggleSubscription: vi.fn(),
|
||||
getTotal: () => 2000,
|
||||
getSubtotal: () => 2000,
|
||||
getDiscount: () => 0,
|
||||
coupon: null,
|
||||
applyCoupon: vi.fn(),
|
||||
addItem: vi.fn(),
|
||||
} as unknown as ReturnType<typeof useCartStore>);
|
||||
|
||||
render(<CartDrawer isOpen={true} onClose={vi.fn()} onCheckout={vi.fn()} />);
|
||||
it('handles item quantity increment and decrement clicks', () => {
|
||||
render(
|
||||
<CartDrawer
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onCheckout={mockOnCheckout}
|
||||
/>
|
||||
);
|
||||
|
||||
const plusBtn = screen.getByTestId('plus-btn');
|
||||
const minusBtn = screen.getByTestId('minus-btn');
|
||||
@@ -124,7 +215,222 @@ describe('CartDrawer', () => {
|
||||
expect(mockUpdateQuantity).toHaveBeenCalledWith('canhydrox-gag', 1);
|
||||
});
|
||||
|
||||
it('hides prices, total and coupon code when showPrices is false in catalog mode', () => {
|
||||
it('shows inline delete confirmation overlay and deletes item on confirm', () => {
|
||||
render(
|
||||
<CartDrawer
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onCheckout={mockOnCheckout}
|
||||
/>
|
||||
);
|
||||
|
||||
const deleteBtn = screen.getByTestId('cart-item-delete-btn');
|
||||
fireEvent.click(deleteBtn);
|
||||
|
||||
expect(
|
||||
screen.getByText('مطمئنی میخوای این محصول رو حذف کنی؟')
|
||||
).toBeInTheDocument();
|
||||
|
||||
const confirmDeleteBtn = screen.getByRole('button', { name: 'حذف' });
|
||||
fireEvent.click(confirmDeleteBtn);
|
||||
|
||||
expect(mockRemoveItem).toHaveBeenCalledWith('canhydrox-gag');
|
||||
expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('Canhydrox GAG'));
|
||||
});
|
||||
|
||||
it('cancels inline delete confirmation overlay when cancel is clicked', async () => {
|
||||
render(
|
||||
<CartDrawer
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onCheckout={mockOnCheckout}
|
||||
/>
|
||||
);
|
||||
|
||||
const deleteBtn = screen.getByTestId('cart-item-delete-btn');
|
||||
fireEvent.click(deleteBtn);
|
||||
|
||||
expect(
|
||||
screen.getByText('مطمئنی میخوای این محصول رو حذف کنی؟')
|
||||
).toBeInTheDocument();
|
||||
|
||||
const cancelBtn = screen.getByRole('button', { name: 'لغو' });
|
||||
fireEvent.click(cancelBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.queryByText('مطمئنی میخوای این محصول رو حذف کنی؟')
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
expect(mockRemoveItem).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('handles coupon code submission successfully and shows applied coupon badge', async () => {
|
||||
mockApplyCoupon.mockResolvedValue(true);
|
||||
|
||||
const { rerender } = render(
|
||||
<CartDrawer
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onCheckout={mockOnCheckout}
|
||||
/>
|
||||
);
|
||||
|
||||
const couponInput = screen.getByPlaceholderText('CANINO2024');
|
||||
fireEvent.change(couponInput, { target: { value: 'OFF20' } });
|
||||
|
||||
const applyBtn = screen.getByRole('button', { name: 'اعمال' });
|
||||
fireEvent.click(applyBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockApplyCoupon).toHaveBeenCalledWith('OFF20');
|
||||
});
|
||||
|
||||
// Rerender with coupon in store
|
||||
vi.mocked(useCartStore).mockReturnValue({
|
||||
items: [{ product: mockProduct as any, quantity: 2 }],
|
||||
updateQuantity: mockUpdateQuantity,
|
||||
removeItem: mockRemoveItem,
|
||||
isSubscribed: false,
|
||||
toggleSubscription: mockToggleSubscription,
|
||||
getTotal: () => 1600,
|
||||
getSubtotal: () => 2000,
|
||||
getDiscount: () => 400,
|
||||
coupon: { code: 'OFF20', discount: 0.2 },
|
||||
applyCoupon: mockApplyCoupon,
|
||||
addItem: mockAddItem,
|
||||
} as any);
|
||||
|
||||
rerender(
|
||||
<CartDrawer
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onCheckout={mockOnCheckout}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText(/کد OFF20/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/مجموع تخفیفها/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/-۴۰۰/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows error state when applying invalid coupon code', async () => {
|
||||
mockApplyCoupon.mockResolvedValue(false);
|
||||
|
||||
render(
|
||||
<CartDrawer
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onCheckout={mockOnCheckout}
|
||||
/>
|
||||
);
|
||||
|
||||
const couponInput = screen.getByPlaceholderText('CANINO2024');
|
||||
fireEvent.change(couponInput, { target: { value: 'INVALID' } });
|
||||
|
||||
const applyBtn = screen.getByRole('button', { name: 'اعمال' });
|
||||
fireEvent.click(applyBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockApplyCoupon).toHaveBeenCalledWith('INVALID');
|
||||
expect(couponInput).toHaveClass('border-red-300');
|
||||
});
|
||||
expect(mockOnCheckout).not.toHaveBeenCalled();
|
||||
expect(screen.queryByText(/حذف کد/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('triggers checkout callback when checkout button is clicked', () => {
|
||||
render(
|
||||
<CartDrawer
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onCheckout={mockOnCheckout}
|
||||
/>
|
||||
);
|
||||
|
||||
const checkoutBtn = screen.getByText(/ثبت نهایی و تسویه حساب/);
|
||||
fireEvent.click(checkoutBtn);
|
||||
|
||||
expect(mockOnCheckout).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('toggles subscription for logged-in user', () => {
|
||||
render(
|
||||
<CartDrawer
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onCheckout={mockOnCheckout}
|
||||
/>
|
||||
);
|
||||
|
||||
const subscriptionToggle = screen.getByText(/سامانه تمدید هوشمند/).closest('div[class*="cursor-pointer"]');
|
||||
expect(subscriptionToggle).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(subscriptionToggle!);
|
||||
expect(mockToggleSubscription).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('opens auth modal if logged-out user tries to toggle refill subscription', () => {
|
||||
vi.mocked(useUserStore).mockReturnValue({
|
||||
isLoggedIn: false,
|
||||
profile: null,
|
||||
} as any);
|
||||
|
||||
render(
|
||||
<CartDrawer
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onCheckout={mockOnCheckout}
|
||||
/>
|
||||
);
|
||||
|
||||
const subscriptionToggle = screen.getByText(/سامانه تمدید هوشمند/).closest('div[class*="cursor-pointer"]');
|
||||
fireEvent.click(subscriptionToggle!);
|
||||
|
||||
expect(toast.info).toHaveBeenCalledWith(expect.stringContaining('وارد حساب کاربری خود شوید'));
|
||||
expect(screen.getByTestId('auth-modal')).toBeInTheDocument();
|
||||
expect(mockToggleSubscription).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('fetches and renders smart cross-sell product and adds to cart when clicked', async () => {
|
||||
render(
|
||||
<CartDrawer
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onCheckout={mockOnCheckout}
|
||||
/>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(productService.getProducts).toHaveBeenCalledWith({ limit: 999 });
|
||||
expect(screen.getByText('Lachs-Öl')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const crossSellAddBtn = screen.getByText('Lachs-Öl').closest('div')!.parentElement!.querySelector('button')!;
|
||||
fireEvent.click(crossSellAddBtn);
|
||||
|
||||
expect(mockAddItem).toHaveBeenCalledWith(mockSuggestedProduct, 1);
|
||||
});
|
||||
|
||||
it('closes drawer on header close button click', () => {
|
||||
render(
|
||||
<CartDrawer
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onCheckout={mockOnCheckout}
|
||||
/>
|
||||
);
|
||||
|
||||
// Header close button has X icon
|
||||
const closeButtons = screen.getAllByRole('button');
|
||||
const headerCloseBtn = closeButtons.find(b => b.querySelector('svg.lucide-x'));
|
||||
expect(headerCloseBtn).toBeDefined();
|
||||
|
||||
fireEvent.click(headerCloseBtn!);
|
||||
expect(mockOnClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('hides prices and financial controls when catalog mode showPrices is false', () => {
|
||||
vi.mocked(useCatalogMode).mockReturnValue({
|
||||
isCatalogOnly: true,
|
||||
showPrices: false,
|
||||
@@ -138,23 +444,15 @@ describe('CartDrawer', () => {
|
||||
orderDisabledMessage: '',
|
||||
});
|
||||
|
||||
vi.mocked(useCartStore).mockReturnValue({
|
||||
items: [{ product: mockProduct, quantity: 2 }],
|
||||
updateQuantity: vi.fn(),
|
||||
removeItem: vi.fn(),
|
||||
isSubscribed: false,
|
||||
toggleSubscription: vi.fn(),
|
||||
getTotal: () => 2000,
|
||||
getSubtotal: () => 2000,
|
||||
getDiscount: () => 0,
|
||||
coupon: null,
|
||||
applyCoupon: vi.fn(),
|
||||
addItem: vi.fn(),
|
||||
} as unknown as ReturnType<typeof useCartStore>);
|
||||
render(
|
||||
<CartDrawer
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onCheckout={mockOnCheckout}
|
||||
/>
|
||||
);
|
||||
|
||||
render(<CartDrawer isOpen={true} onClose={vi.fn()} onCheckout={vi.fn()} />);
|
||||
|
||||
expect(screen.getByText('Canhydrox GAG')).toBeInTheDocument();
|
||||
expect(screen.getByText('کانهیدروکس گگ')).toBeInTheDocument();
|
||||
expect(screen.queryByText('کد تخفیف اختصاصی')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('مجموع قابل پرداخت')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('تعداد کل اقلام انتخابی')).toBeInTheDocument();
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import React from 'react';
|
||||
import {render,screen,fireEvent,cleanup} from '@testing-library/react';
|
||||
import {vi,afterEach,it,expect} from 'vitest';
|
||||
import CatalogPageSpread from '../catalog/CatalogPageSpread';
|
||||
import type {Product} from '../../lib/data/products';
|
||||
vi.mock('../../lib/store/settingsStore',()=>({useSettingsStore:(fn:(s:unknown)=>unknown)=>fn({getText:()=>''})}));
|
||||
vi.mock('../SafeImage',()=>({default:({alt}:{alt:string})=><img alt={alt}/>}));
|
||||
afterEach(cleanup);
|
||||
const product={id:'1',name:'Joint tabs',artNo:'A1',category:'مفاصل',description:'<b>Clinical description</b>',dosage_logic:'First dosage step؛Second dosage step؛Third dosage step؛Fourth dosage step',symptoms:['Mobility'],main_ingredients:['Calcium','Zinc'],suitableFor:'both',unit:'tabs',image:'/x.png'} as unknown as Product;
|
||||
it.each(['cover','toc','backcover'] as const)('renders %s without product',pageType=>{const {container}=render(<CatalogPageSpread pageType={pageType} pageNumber={1} totalPages={4}/>);expect(container.textContent?.length).toBeGreaterThan(20);});
|
||||
it('renders nothing for missing product',()=>{const {container}=render(<CatalogPageSpread pageType="product" pageNumber={3} totalPages={4}/>);expect(container).toBeEmptyDOMElement();});
|
||||
it('strips markup and caps dosage steps at three',()=>{render(<CatalogPageSpread pageType="product" pageNumber={3} totalPages={4} product={product}/>);expect(screen.getByText('Joint tabs')).toBeInTheDocument();expect(screen.getByText('Clinical description')).toBeInTheDocument();expect(screen.getByText(/Calcium، Zinc/)).toBeInTheDocument();expect(screen.getByText('سگ و گربه')).toBeInTheDocument();expect(screen.getByText('Third dosage step')).toBeInTheDocument();expect(screen.queryByText('Fourth dosage step')).not.toBeInTheDocument();});
|
||||
it.each([['cat','مخصوص گربه'],['dog','مخصوص سگ']])('labels species %s',(suitableFor,label)=>{render(<CatalogPageSpread pageType="product" pageNumber={4} totalPages={6} product={{...product,suitableFor} as Product}/>);expect(screen.getByText(label)).toBeInTheDocument();});
|
||||
it('jumps from TOC to category start',()=>{const jump=vi.fn();render(<CatalogPageSpread pageType="toc" pageNumber={2} totalPages={8} onJumpToPage={jump} categoriesList={[{id:'joints',name:'Joint category',color:'#000',lightBg:'#fff',borderBg:'#111',icon:()=>null,tagline:'Clinical joints',startPage:3}]}/>);fireEvent.click(screen.getByText('Joint category'));expect(jump).toHaveBeenCalledWith(3);});
|
||||
@@ -0,0 +1,392 @@
|
||||
"use client";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import CheckoutPage from "../CheckoutPage";
|
||||
import { useCartStore } from "../../lib/store/cartStore";
|
||||
import { usePetStore } from "../../lib/store/usePetStore";
|
||||
import { useUserStore } from "../../lib/store/userStore";
|
||||
import { useSettingsStore } from "../../lib/store/settingsStore";
|
||||
import { useCatalogMode } from "../../lib/useCatalogMode";
|
||||
import { toast } from "sonner";
|
||||
import api from "../../lib/services/api";
|
||||
|
||||
const mockRouterPush = vi.fn();
|
||||
const mockRouterBack = vi.fn();
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({
|
||||
push: mockRouterPush,
|
||||
back: mockRouterBack,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("sonner", () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/services/api", () => ({
|
||||
default: {
|
||||
post: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/useCatalogMode", () => ({
|
||||
useCatalogMode: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/store/cartStore", () => ({
|
||||
useCartStore: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/store/usePetStore", () => ({
|
||||
usePetStore: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/store/userStore", () => ({
|
||||
useUserStore: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/store/settingsStore", () => ({
|
||||
useSettingsStore: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockProductA = {
|
||||
id: "canina-v25",
|
||||
name: "Canina V25 ویتامینه",
|
||||
price: "۴۵۰,۰۰۰ تومان",
|
||||
priceValue: 450000,
|
||||
packageSize: 30,
|
||||
category: "vitamins",
|
||||
image: "/v25.png",
|
||||
};
|
||||
|
||||
describe("CheckoutPage Component", () => {
|
||||
const mockClearCart = vi.fn();
|
||||
const mockAddOrder = vi.fn();
|
||||
const mockSetCharityDonation = vi.fn();
|
||||
const mockApplyCoupon = vi.fn();
|
||||
|
||||
const mockAddAddress = vi.fn().mockResolvedValue({});
|
||||
const mockUpdateProfile = vi.fn().mockResolvedValue({});
|
||||
const mockFetchProfile = vi.fn().mockResolvedValue({});
|
||||
const mockSetAuthModalOpen = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Default Catalog Mode
|
||||
vi.mocked(useCatalogMode).mockReturnValue({
|
||||
isCatalogOnly: false,
|
||||
allowCheckout: true,
|
||||
showPrices: true,
|
||||
allowCart: true,
|
||||
showPreorderBtn: false,
|
||||
showOrders: true,
|
||||
showWallet: true,
|
||||
showCharity: true,
|
||||
orderDisabledTitle: "امکان ثبت سفارش وجود ندارد",
|
||||
orderDisabledMessage: "فروشگاه موقتاً در حالت کاتالوگ است.",
|
||||
});
|
||||
|
||||
// Default Cart Store
|
||||
const cartState = {
|
||||
items: [
|
||||
{
|
||||
product: mockProductA,
|
||||
quantity: 2,
|
||||
},
|
||||
],
|
||||
getTotal: () => 900000,
|
||||
getSubtotal: () => 900000,
|
||||
isSubscribed: false,
|
||||
charityDonation: 0,
|
||||
setCharityDonation: mockSetCharityDonation,
|
||||
addOrder: mockAddOrder,
|
||||
clearCart: mockClearCart,
|
||||
applyCoupon: mockApplyCoupon,
|
||||
};
|
||||
vi.mocked(useCartStore).mockReturnValue(cartState as unknown as ReturnType<typeof useCartStore>);
|
||||
(useCartStore as unknown as { getState: () => typeof cartState }).getState = () => cartState;
|
||||
|
||||
// Default Pet Store
|
||||
const petState = {
|
||||
pets: [
|
||||
{
|
||||
id: "pet-1",
|
||||
name: "میلو",
|
||||
breed: "هاسکی",
|
||||
type: "سگ",
|
||||
consumptions: [],
|
||||
},
|
||||
],
|
||||
activePetId: "pet-1",
|
||||
getActivePet: () => ({
|
||||
id: "pet-1",
|
||||
name: "میلو",
|
||||
breed: "هاسکی",
|
||||
type: "سگ",
|
||||
consumptions: [],
|
||||
}),
|
||||
updatePet: vi.fn(),
|
||||
};
|
||||
vi.mocked(usePetStore).mockReturnValue(petState as unknown as ReturnType<typeof usePetStore>);
|
||||
(usePetStore as unknown as { getState: () => typeof petState }).getState = () => petState;
|
||||
|
||||
// Default User Store
|
||||
const userState = {
|
||||
isLoggedIn: true,
|
||||
profile: {
|
||||
id: "usr-1",
|
||||
firstName: "علی",
|
||||
lastName: "رضایی",
|
||||
mobile: "09121112233",
|
||||
walletBalance: 2000000,
|
||||
addresses: [
|
||||
{
|
||||
id: "addr-1",
|
||||
title: "منزل اصلی",
|
||||
receptorName: "علی رضایی",
|
||||
phone: "09121112233",
|
||||
province: "تهران",
|
||||
city: "تهران",
|
||||
detail: "خیابان ولیعصر پلاک ۱",
|
||||
zipCode: "1234567890",
|
||||
isDefault: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
addAddress: mockAddAddress,
|
||||
updateProfile: mockUpdateProfile,
|
||||
fetchProfile: mockFetchProfile,
|
||||
setAuthModalOpen: mockSetAuthModalOpen,
|
||||
updateAddress: vi.fn(),
|
||||
};
|
||||
vi.mocked(useUserStore).mockReturnValue(userState as unknown as ReturnType<typeof useUserStore>);
|
||||
(useUserStore as unknown as { getState: () => typeof userState }).getState = () => userState;
|
||||
|
||||
// Default Settings Store
|
||||
const settingsState = {
|
||||
getText: (key: string, def: string) => {
|
||||
if (key === "free_shipping_threshold") return "2000000";
|
||||
if (key === "shipping_fee") return "50000";
|
||||
if (key === "CHARITY_ROUND_STEP") return "10000";
|
||||
return def;
|
||||
},
|
||||
getBoolean: (key: string, def: boolean) => def,
|
||||
};
|
||||
vi.mocked(useSettingsStore).mockImplementation(
|
||||
(selector: (s: typeof settingsState) => unknown) => selector(settingsState) as ReturnType<typeof selector>
|
||||
);
|
||||
(useSettingsStore as unknown as { getState: () => typeof settingsState }).getState = () => settingsState;
|
||||
});
|
||||
|
||||
it("renders catalog-only banner when order/checkout is disabled", () => {
|
||||
vi.mocked(useCatalogMode).mockReturnValue({
|
||||
isCatalogOnly: true,
|
||||
allowCheckout: false,
|
||||
showPrices: false,
|
||||
allowCart: false,
|
||||
showPreorderBtn: false,
|
||||
showOrders: false,
|
||||
showWallet: false,
|
||||
showCharity: false,
|
||||
orderDisabledTitle: "ثبت سفارش در حال حاضر غیرفعال است",
|
||||
orderDisabledMessage: "لطفاً با واحد فروش تماس حاصل فرمایید.",
|
||||
});
|
||||
|
||||
render(<CheckoutPage />);
|
||||
|
||||
expect(screen.getByText("ثبت سفارش در حال حاضر غیرفعال است")).toBeInTheDocument();
|
||||
expect(screen.getByText("لطفاً با واحد فروش تماس حاصل فرمایید.")).toBeInTheDocument();
|
||||
expect(screen.getByText("مشاهده کاتالوگ")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders empty cart state when user cart is empty", () => {
|
||||
const emptyCartState = {
|
||||
items: [],
|
||||
getTotal: () => 0,
|
||||
getSubtotal: () => 0,
|
||||
isSubscribed: false,
|
||||
charityDonation: 0,
|
||||
setCharityDonation: mockSetCharityDonation,
|
||||
addOrder: mockAddOrder,
|
||||
clearCart: mockClearCart,
|
||||
applyCoupon: mockApplyCoupon,
|
||||
};
|
||||
vi.mocked(useCartStore).mockReturnValue(emptyCartState as unknown as ReturnType<typeof useCartStore>);
|
||||
(useCartStore as unknown as { getState: () => typeof emptyCartState }).getState = () => emptyCartState;
|
||||
|
||||
render(<CheckoutPage />);
|
||||
|
||||
expect(screen.getByText("سبد خرید شما خالی است")).toBeInTheDocument();
|
||||
expect(screen.getByText("بازگشت به فروشگاه")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders order items, stored address, and cost summary properly", () => {
|
||||
render(<CheckoutPage />);
|
||||
|
||||
expect(screen.getByText("اطلاعات تحویل و گیرنده")).toBeInTheDocument();
|
||||
expect(screen.getByText("Canina V25 ویتامینه")).toBeInTheDocument();
|
||||
expect(screen.getByText("خلاصه سفارش")).toBeInTheDocument();
|
||||
expect(screen.getByText("شیوه پرداخت")).toBeInTheDocument();
|
||||
|
||||
// Stored address should be displayed
|
||||
expect(screen.getByText("منزل اصلی")).toBeInTheDocument();
|
||||
expect(screen.getByText(/تهران، تهران، خیابان ولیعصر پلاک ۱/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("prevents finalize and opens login modal if user is not logged in", async () => {
|
||||
const unauthenticatedUser = {
|
||||
isLoggedIn: false,
|
||||
profile: { addresses: [] },
|
||||
addAddress: mockAddAddress,
|
||||
updateProfile: mockUpdateProfile,
|
||||
fetchProfile: mockFetchProfile,
|
||||
setAuthModalOpen: mockSetAuthModalOpen,
|
||||
};
|
||||
vi.mocked(useUserStore).mockReturnValue(unauthenticatedUser as unknown as ReturnType<typeof useUserStore>);
|
||||
(useUserStore as unknown as { getState: () => typeof unauthenticatedUser }).getState = () => unauthenticatedUser;
|
||||
|
||||
render(<CheckoutPage />);
|
||||
|
||||
const submitBtn = screen.getByText("پرداخت و تکمیل سفارش");
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
expect(toast.error).toHaveBeenCalledWith(
|
||||
expect.stringContaining("جهت تکمیل خرید و ثبت سفارش، لطفاً ابتدا وارد حساب کاربری خود شوید.")
|
||||
);
|
||||
expect(mockSetAuthModalOpen).toHaveBeenCalledWith(true);
|
||||
expect(mockAddOrder).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("successfully finalizes order and redirects on valid checkout", async () => {
|
||||
mockAddOrder.mockResolvedValue("ORDER-CANINA-101");
|
||||
|
||||
render(<CheckoutPage />);
|
||||
|
||||
// Select the address radio button to ensure selectedAddressId is set
|
||||
const addressCard = screen.getByText("منزل اصلی").closest("div");
|
||||
if (addressCard) fireEvent.click(addressCard);
|
||||
|
||||
const submitBtn = screen.getByText("پرداخت و تکمیل سفارش");
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockAddOrder).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
expect(mockAddOrder).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
items: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
product: mockProductA,
|
||||
quantity: 2,
|
||||
}),
|
||||
]),
|
||||
paymentMethod: "card",
|
||||
})
|
||||
);
|
||||
|
||||
expect(mockClearCart).toHaveBeenCalledTimes(1);
|
||||
expect(toast.success).toHaveBeenCalledWith("سفارش شما با موفقیت ثبت شد!");
|
||||
expect(mockRouterPush).toHaveBeenCalledWith("/checkout/success/ORDER-CANINA-101");
|
||||
});
|
||||
|
||||
it("preserves cart and avoids fulfillment when gateway returns no payment URL", async () => {
|
||||
mockAddOrder.mockResolvedValueOnce("ORDER-PENDING");
|
||||
vi.mocked(api.post).mockResolvedValueOnce({ data: {} });
|
||||
render(<CheckoutPage />);
|
||||
fireEvent.click(screen.getByRole("radio", { name: "" }));
|
||||
fireEvent.click(screen.getByText("درگاه پرداخت اینترنتی (زیبال / شتاب)"));
|
||||
fireEvent.click(screen.getByText("پرداخت و تکمیل سفارش"));
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith("خطا در ایجاد تراکنش پرداخت زیبال"));
|
||||
await waitFor(() => expect(screen.getByText("پرداخت و تکمیل سفارش").closest("button")).not.toBeDisabled());
|
||||
expect(api.post).toHaveBeenCalledWith('/payment/zibal/initiate', { orderId: 'ORDER-PENDING' });
|
||||
expect(mockClearCart).not.toHaveBeenCalled();
|
||||
expect(usePetStore.getState().updatePet).not.toHaveBeenCalled();
|
||||
expect(toast.success).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps cart and reports backend rejection without navigating", async () => {
|
||||
mockAddOrder.mockRejectedValueOnce({ response: { data: { message: 'موجودی کافی نیست' } } });
|
||||
render(<CheckoutPage />);
|
||||
fireEvent.click(screen.getByRole('radio', { name: '' }));
|
||||
fireEvent.click(screen.getByText('پرداخت و تکمیل سفارش'));
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('خطا در ثبت سفارش: موجودی کافی نیست'));
|
||||
expect(mockClearCart).not.toHaveBeenCalled();
|
||||
expect(mockRouterPush).not.toHaveBeenCalled();
|
||||
expect(usePetStore.getState().updatePet).not.toHaveBeenCalled();
|
||||
await waitFor(() => expect(screen.getByText('پرداخت و تکمیل سفارش').closest('button')).not.toBeDisabled());
|
||||
});
|
||||
|
||||
it("preserves cart on gateway network failure", async () => {
|
||||
mockAddOrder.mockResolvedValueOnce('ORDER-NETWORK');
|
||||
vi.mocked(api.post).mockRejectedValueOnce({ response: { data: { message: 'درگاه در دسترس نیست' } } });
|
||||
render(<CheckoutPage />);
|
||||
fireEvent.click(screen.getByRole('radio', { name: '' }));
|
||||
fireEvent.click(screen.getByText('درگاه پرداخت اینترنتی (زیبال / شتاب)'));
|
||||
fireEvent.click(screen.getByText('پرداخت و تکمیل سفارش'));
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('درگاه در دسترس نیست'));
|
||||
expect(mockRouterPush).toHaveBeenCalledWith('/checkout/success/ORDER-NETWORK');
|
||||
expect(mockClearCart).not.toHaveBeenCalled();
|
||||
expect(usePetStore.getState().updatePet).not.toHaveBeenCalled();
|
||||
expect(toast.success).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("checks wallet balance and shows top-up modal if wallet balance is insufficient", async () => {
|
||||
const poorUserState = {
|
||||
isLoggedIn: true,
|
||||
profile: {
|
||||
id: "usr-poor",
|
||||
firstName: "علی",
|
||||
lastName: "رضایی",
|
||||
mobile: "09121112233",
|
||||
walletBalance: 100000, // Total is 900,000 + 50,000 = 950,000
|
||||
addresses: [
|
||||
{
|
||||
id: "addr-1",
|
||||
title: "منزل اصلی",
|
||||
receptorName: "علی رضایی",
|
||||
phone: "09121112233",
|
||||
province: "تهران",
|
||||
city: "تهران",
|
||||
detail: "خیابان ولیعصر پلاک ۱",
|
||||
zipCode: "1234567890",
|
||||
isDefault: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
addAddress: mockAddAddress,
|
||||
updateProfile: mockUpdateProfile,
|
||||
fetchProfile: mockFetchProfile,
|
||||
setAuthModalOpen: mockSetAuthModalOpen,
|
||||
};
|
||||
vi.mocked(useUserStore).mockReturnValue(poorUserState as unknown as ReturnType<typeof useUserStore>);
|
||||
(useUserStore as unknown as { getState: () => typeof poorUserState }).getState = () => poorUserState;
|
||||
|
||||
render(<CheckoutPage />);
|
||||
|
||||
// Select stored address explicitly
|
||||
const addressCard = screen.getByText("منزل اصلی").closest("div");
|
||||
if (addressCard) fireEvent.click(addressCard);
|
||||
|
||||
// Select wallet payment method
|
||||
const walletOption = screen.getByText("اعتبار حساب (کیف پول)");
|
||||
fireEvent.click(walletOption);
|
||||
|
||||
const submitBtn = screen.getByText("پرداخت و تکمیل سفارش");
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(toast.error).toHaveBeenCalledWith(
|
||||
expect.stringContaining("موجودی کیف پول شما")
|
||||
);
|
||||
});
|
||||
expect(mockAddOrder).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
"use client";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import ContactFormClient from "../ContactFormClient";
|
||||
import api from "../../lib/services/api";
|
||||
|
||||
vi.mock("../../lib/services/api", () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("ContactFormClient Component", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("fetches and renders contact info items", async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({
|
||||
data: [
|
||||
{ key: "phone", title: "شماره تماس", value: "021-12345678" },
|
||||
{ key: "email", title: "پست الکترونیک", value: "support@canina.ir" },
|
||||
],
|
||||
});
|
||||
|
||||
render(<ContactFormClient />);
|
||||
|
||||
expect(api.get).toHaveBeenCalledWith("/contact/info");
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("021-12345678")).toBeInTheDocument();
|
||||
expect(screen.getByText("support@canina.ir")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("shows error when required fields are empty on submit", async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: [] });
|
||||
const { container } = render(<ContactFormClient />);
|
||||
|
||||
const form = container.querySelector("form");
|
||||
expect(form).not.toBeNull();
|
||||
fireEvent.submit(form!);
|
||||
|
||||
expect(
|
||||
screen.getByText("لطفاً نام، شماره موبایل و متن پیام را وارد کنید.")
|
||||
).toBeInTheDocument();
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("validates Iranian mobile phone number format", async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: [] });
|
||||
const { container } = render(<ContactFormClient />);
|
||||
|
||||
const nameInput = screen.getByPlaceholderText("مثال: علی محمدی");
|
||||
const phoneInput = screen.getByPlaceholderText("09123456789");
|
||||
const messageInput = screen.getByPlaceholderText("متن درخواست یا پیام خود را بنویسید...");
|
||||
const form = container.querySelector("form");
|
||||
|
||||
fireEvent.change(nameInput, { target: { value: "علی محمدی" } });
|
||||
fireEvent.change(phoneInput, { target: { value: "123456" } }); // Invalid phone
|
||||
fireEvent.change(messageInput, { target: { value: "سلام، من سوالی درباره مکمل مفاصل دارم." } });
|
||||
|
||||
fireEvent.submit(form!);
|
||||
|
||||
expect(
|
||||
screen.getByText("شماره همراه وارد شده معتبر نیست. (مثال: ۰۹۱۲۳۴۵۶۷۸۹)")
|
||||
).toBeInTheDocument();
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("successfully submits form and displays success state with reset button", async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: [] });
|
||||
vi.mocked(api.post).mockResolvedValueOnce({ data: { success: true } });
|
||||
|
||||
const { container } = render(<ContactFormClient />);
|
||||
|
||||
const nameInput = screen.getByPlaceholderText("مثال: علی محمدی");
|
||||
const phoneInput = screen.getByPlaceholderText("09123456789");
|
||||
const subjectInput = screen.getByPlaceholderText("مثال: مشاوره تخصصی مکمل یا خرید عمده");
|
||||
const messageInput = screen.getByPlaceholderText("متن درخواست یا پیام خود را بنویسید...");
|
||||
const form = container.querySelector("form");
|
||||
|
||||
fireEvent.change(nameInput, { target: { value: "سارا حسینی" } });
|
||||
fireEvent.change(phoneInput, { target: { value: "09129876543" } });
|
||||
fireEvent.change(subjectInput, { target: { value: "درخواست نمایندگی" } });
|
||||
fireEvent.change(messageInput, { target: { value: "با سلام، شرایط اخذ نمایندگی چیست؟" } });
|
||||
|
||||
fireEvent.submit(form!);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith("/contact", {
|
||||
name: "سارا حسینی",
|
||||
phone: "09129876543",
|
||||
subject: "درخواست نمایندگی",
|
||||
message: "با سلام، شرایط اخذ نمایندگی چیست؟",
|
||||
});
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("پیام شما با موفقیت ثبت شد")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Reset and send another message
|
||||
const sendAnotherBtn = screen.getByText("ارسال پیام جدید");
|
||||
fireEvent.click(sendAnotherBtn);
|
||||
|
||||
expect(screen.getByTestId("contact-form-submit-btn")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("handles submission failure and displays error message", async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: [] });
|
||||
vi.mocked(api.post).mockRejectedValueOnce({
|
||||
response: { data: { message: "خطا در سرور، لطفاً بعداً تلاش کنید." } },
|
||||
});
|
||||
|
||||
const { container } = render(<ContactFormClient />);
|
||||
|
||||
const nameInput = screen.getByPlaceholderText("مثال: علی محمدی");
|
||||
const phoneInput = screen.getByPlaceholderText("09123456789");
|
||||
const messageInput = screen.getByPlaceholderText("متن درخواست یا پیام خود را بنویسید...");
|
||||
const form = container.querySelector("form");
|
||||
|
||||
fireEvent.change(nameInput, { target: { value: "سارا حسینی" } });
|
||||
fireEvent.change(phoneInput, { target: { value: "09129876543" } });
|
||||
fireEvent.change(messageInput, { target: { value: "متن پیام" } });
|
||||
|
||||
fireEvent.submit(form!);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("خطا در سرور، لطفاً بعداً تلاش کنید.")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import DeleteConfirmModal from '../DeleteConfirmModal';
|
||||
|
||||
vi.mock('motion/react', () => ({
|
||||
motion: {
|
||||
div: ({ children, className, onClick }: any) => (
|
||||
<div className={className} onClick={onClick}>
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
AnimatePresence: ({ children }: any) => <>{children}</>,
|
||||
}));
|
||||
|
||||
describe('DeleteConfirmModal Component', () => {
|
||||
it('does not render anything when isOpen is false', () => {
|
||||
const { container } = render(
|
||||
<DeleteConfirmModal
|
||||
isOpen={false}
|
||||
onClose={vi.fn()}
|
||||
onConfirm={vi.fn()}
|
||||
title="حذف آیتم"
|
||||
message="آیا مطمئن هستید؟"
|
||||
/>,
|
||||
);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('renders modal content correctly when isOpen is true', () => {
|
||||
render(
|
||||
<DeleteConfirmModal
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
onConfirm={vi.fn()}
|
||||
title="حذف آدرس"
|
||||
message="آدرس مورد نظر به طور کامل حذف خواهد شد."
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByText('حذف آدرس')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText('آدرس مورد نظر به طور کامل حذف خواهد شد.'),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText('خیر، بماند')).toBeInTheDocument();
|
||||
expect(screen.getByText('بله، حذف شود')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onClose when cancel button is clicked', () => {
|
||||
const handleClose = vi.fn();
|
||||
render(
|
||||
<DeleteConfirmModal
|
||||
isOpen={true}
|
||||
onClose={handleClose}
|
||||
onConfirm={vi.fn()}
|
||||
title="حذف پت"
|
||||
message="آیا مطمئن هستید؟"
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByText('خیر، بماند'));
|
||||
expect(handleClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('calls onConfirm AND onClose when confirm button is clicked', () => {
|
||||
const handleClose = vi.fn();
|
||||
const handleConfirm = vi.fn();
|
||||
render(
|
||||
<DeleteConfirmModal
|
||||
isOpen={true}
|
||||
onClose={handleClose}
|
||||
onConfirm={handleConfirm}
|
||||
title="حذف پت"
|
||||
message="آیا مطمئن هستید؟"
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByText('بله، حذف شود'));
|
||||
expect(handleConfirm).toHaveBeenCalledTimes(1);
|
||||
expect(handleClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import EnamadBadge from '../EnamadBadge';
|
||||
|
||||
describe('EnamadBadge Component', () => {
|
||||
it('renders the enamad badge container with title and subtext', () => {
|
||||
render(<EnamadBadge />);
|
||||
expect(screen.getByText('نماد اعتماد الکترونیکی (eNamad)')).toBeInTheDocument();
|
||||
expect(screen.getByText('صادر شده توسط مرکز توسعه تجارت الکترونیکی (وزارت صمت)')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('contains sanitized enamad link inside the badge wrapper', () => {
|
||||
const { container } = render(<EnamadBadge />);
|
||||
const link = container.querySelector('a');
|
||||
expect(link).toBeInTheDocument();
|
||||
expect(link?.getAttribute('href')).toContain('trustseal.enamad.ir');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { ErrorBoundary } from '../ErrorBoundary';
|
||||
|
||||
// Helper component that throws an error during rendering
|
||||
const ProblemChild = ({ shouldThrow = true }: { shouldThrow?: boolean }) => {
|
||||
if (shouldThrow) {
|
||||
throw new Error('Test render crash');
|
||||
}
|
||||
return <div>محتوای سالم کامپوننت</div>;
|
||||
};
|
||||
|
||||
describe('ErrorBoundary Component', () => {
|
||||
let consoleErrorSpy: any;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
consoleErrorSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('renders children normally when there is no error', () => {
|
||||
render(
|
||||
<ErrorBoundary>
|
||||
<ProblemChild shouldThrow={false} />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
|
||||
expect(screen.getByText('محتوای سالم کامپوننت')).toBeInTheDocument();
|
||||
expect(screen.queryByText('متأسفانه خطایی رخ داده است')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('catches render errors and displays fallback UI', () => {
|
||||
render(
|
||||
<ErrorBoundary>
|
||||
<ProblemChild shouldThrow={true} />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
|
||||
expect(screen.getByText('متأسفانه خطایی رخ داده است')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText('مشکلی در بارگذاری این بخش پیش آمده است. لطفاً برای ادامه دوباره تلاش کنید.')
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /تلاش مجدد/ })).toBeInTheDocument();
|
||||
expect(screen.getByText('Canina Pharma Support')).toBeInTheDocument();
|
||||
expect(screen.queryByText('محتوای سالم کامپوننت')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('logs the uncaught error to console.error via componentDidCatch', () => {
|
||||
render(
|
||||
<ErrorBoundary>
|
||||
<ProblemChild shouldThrow={true} />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
|
||||
expect(consoleErrorSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('triggers window.location.reload when reload/retry button is clicked', () => {
|
||||
const originalLocation = window.location;
|
||||
const reloadMock = vi.fn();
|
||||
|
||||
// Mock window.location.reload
|
||||
Object.defineProperty(window, 'location', {
|
||||
configurable: true,
|
||||
value: {
|
||||
...originalLocation,
|
||||
reload: reloadMock,
|
||||
},
|
||||
});
|
||||
|
||||
render(
|
||||
<ErrorBoundary>
|
||||
<ProblemChild shouldThrow={true} />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
|
||||
const retryButton = screen.getByRole('button', { name: /تلاش مجدد/ });
|
||||
fireEvent.click(retryButton);
|
||||
|
||||
expect(reloadMock).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Restore original location
|
||||
Object.defineProperty(window, 'location', {
|
||||
configurable: true,
|
||||
value: originalLocation,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { NotFoundPage, ServerErrorPage } from '../ErrorPages';
|
||||
|
||||
const mockPush = vi.fn();
|
||||
vi.mock('next/navigation', () => ({
|
||||
useRouter: () => ({
|
||||
push: mockPush,
|
||||
replace: vi.fn(),
|
||||
prefetch: vi.fn(),
|
||||
back: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('ErrorPages Components', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('NotFoundPage (404)', () => {
|
||||
it('renders 404 code, error title, and description message in Persian', () => {
|
||||
render(<NotFoundPage />);
|
||||
|
||||
expect(screen.getByText('۴۰۴')).toBeInTheDocument();
|
||||
expect(screen.getByText('صفحه پیدا نشد!')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText(/متأسفانه صفحهای که به دنبال آن هستید وجود ندارد یا جابجا شده است/)
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /بازگشت به خانه/ })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('navigates to home ("/") when clicking back to home button', () => {
|
||||
render(<NotFoundPage />);
|
||||
|
||||
const homeButton = screen.getByRole('button', { name: /بازگشت به خانه/ });
|
||||
fireEvent.click(homeButton);
|
||||
|
||||
expect(mockPush).toHaveBeenCalledTimes(1);
|
||||
expect(mockPush).toHaveBeenCalledWith('/');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ServerErrorPage (500)', () => {
|
||||
it('renders 500 error heading and explanation text', () => {
|
||||
const mockOnRetry = vi.fn();
|
||||
render(<ServerErrorPage onRetry={mockOnRetry} />);
|
||||
|
||||
expect(screen.getByText('خطای داخلی سیستم')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText(/ارتباط با دیتابیس کنینا با مشکل مواجه شده است/)
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /تلاش مجدد/ })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onRetry callback when clicking retry button', () => {
|
||||
const mockOnRetry = vi.fn();
|
||||
render(<ServerErrorPage onRetry={mockOnRetry} />);
|
||||
|
||||
const retryButton = screen.getByRole('button', { name: /تلاش مجدد/ });
|
||||
fireEvent.click(retryButton);
|
||||
|
||||
expect(mockOnRetry).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
"use client";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import FAQSection from "../FAQSection";
|
||||
import api from "../../lib/services/api";
|
||||
|
||||
// Mock motion/react
|
||||
vi.mock("motion/react", () => ({
|
||||
AnimatePresence: ({ children }: { children: React.ReactNode }) => <>{children}</>,
|
||||
motion: {
|
||||
div: ({ children, ...props }: any) => <div {...props}>{children}</div>,
|
||||
button: ({ children, ...props }: any) => <button {...props}>{children}</button>,
|
||||
span: ({ children, ...props }: any) => <span {...props}>{children}</span>,
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/services/api", () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockSettings: Record<string, string> = {
|
||||
faq_badge: "پاسخ به سوالات پرتکرار",
|
||||
faq_title_1: "سوالات متداول",
|
||||
faq_title_2: "درباره محصولات و سفارش",
|
||||
faq_desc: "پاسخ به متداولترین سوالات درباره استانداردها، دوز مصرفی، ارسال و اصالت مکملهای کنینا.",
|
||||
};
|
||||
|
||||
vi.mock("../../lib/store/settingsStore", () => ({
|
||||
useSettingsStore: (selector: any) =>
|
||||
selector({
|
||||
getText: (key: string, fallback: string) => mockSettings[key] || fallback,
|
||||
}),
|
||||
}));
|
||||
|
||||
describe("FAQSection Component", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("renders loading state initially while fetching FAQs", () => {
|
||||
vi.mocked(api.get).mockReturnValue(new Promise(() => {}));
|
||||
const { container } = render(<FAQSection />);
|
||||
|
||||
const skeletonItems = container.querySelectorAll(".animate-pulse");
|
||||
expect(skeletonItems.length).toBe(3);
|
||||
});
|
||||
|
||||
it("returns null when no FAQs are found after loading", async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: [] });
|
||||
const { container } = render(<FAQSection />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it("renders FAQ list, opens the first FAQ by default, and includes JSON-LD schema", async () => {
|
||||
const mockFaqs = [
|
||||
{
|
||||
id: "faq-1",
|
||||
question: "آیا محصولات کنینا اصل آلمان هستند؟",
|
||||
answer: "بله، تمامی محصولات با ضمانت اصالت ۱۰۰٪ از کمپانی کنینا آلمان وارد میشوند.",
|
||||
order: 1,
|
||||
},
|
||||
{
|
||||
id: "faq-2",
|
||||
question: "چگونه دوز مناسب را برای سگ خود محاسبه کنیم؟",
|
||||
answer: "بر اساس جدول وزنی موجود روی برچسب قوطی یا بخش مشاوره هوشمند.",
|
||||
order: 2,
|
||||
},
|
||||
];
|
||||
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockFaqs });
|
||||
const { container } = render(<FAQSection />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("آیا محصولات کنینا اصل آلمان هستند؟")).toBeInTheDocument();
|
||||
expect(screen.getByText("چگونه دوز مناسب را برای سگ خود محاسبه کنیم؟")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Check first FAQ answer is visible (openIndex defaults to 0)
|
||||
expect(
|
||||
screen.getByText("بله، تمامی محصولات با ضمانت اصالت ۱۰۰٪ از کمپانی کنینا آلمان وارد میشوند.")
|
||||
).toBeInTheDocument();
|
||||
|
||||
// Check JSON-LD script is rendered
|
||||
const script = container.querySelector('script[type="application/ld+json"]');
|
||||
expect(script).not.toBeNull();
|
||||
const schema = JSON.parse(script?.innerHTML || "{}");
|
||||
expect(schema["@type"]).toBe("FAQPage");
|
||||
expect(schema.mainEntity).toHaveLength(2);
|
||||
expect(schema.mainEntity[0].name).toBe("آیا محصولات کنینا اصل آلمان هستند؟");
|
||||
});
|
||||
|
||||
it("toggles accordion when clicking questions", async () => {
|
||||
const mockFaqs = [
|
||||
{
|
||||
id: "faq-1",
|
||||
question: "سوال اول؟",
|
||||
answer: "پاسخ اول",
|
||||
order: 1,
|
||||
},
|
||||
{
|
||||
id: "faq-2",
|
||||
question: "سوال دوم؟",
|
||||
answer: "پاسخ دوم",
|
||||
order: 2,
|
||||
},
|
||||
];
|
||||
|
||||
vi.mocked(api.get).mockResolvedValueOnce({ data: mockFaqs });
|
||||
render(<FAQSection />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("سوال اول؟")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Question 1 is initially open
|
||||
expect(screen.getByText("پاسخ اول")).toBeInTheDocument();
|
||||
expect(screen.queryByText("پاسخ دوم")).not.toBeInTheDocument();
|
||||
|
||||
// Click Question 2 to open it
|
||||
fireEvent.click(screen.getByText("سوال دوم؟"));
|
||||
|
||||
expect(screen.queryByText("پاسخ اول")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("پاسخ دوم")).toBeInTheDocument();
|
||||
|
||||
// Click Question 2 again to close it
|
||||
fireEvent.click(screen.getByText("سوال دوم؟"));
|
||||
expect(screen.queryByText("پاسخ دوم")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("handles api errors gracefully and renders null", async () => {
|
||||
vi.mocked(api.get).mockRejectedValueOnce(new Error("Network Error"));
|
||||
const { container } = render(<FAQSection />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -82,6 +82,6 @@ describe('FeaturedProducts', () => {
|
||||
|
||||
const navBtn = screen.getByText('مشاهده تمامی محصولات');
|
||||
fireEvent.click(navBtn);
|
||||
expect(mockPush).toHaveBeenCalledWith('/shop');
|
||||
expect(navBtn.closest('a')).toHaveAttribute('href', '/shop');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import React from 'react';
|
||||
import {render,screen,fireEvent,act,cleanup} from '@testing-library/react';
|
||||
import {vi,beforeEach,afterEach,it,expect} from 'vitest';
|
||||
import FlipbookCatalog from '../catalog/FlipbookCatalog';
|
||||
import type {Product} from '../../lib/data/products';
|
||||
const {push}=vi.hoisted(()=>({push:vi.fn()}));
|
||||
vi.mock('next/navigation',()=>({useRouter:()=>({push})}));
|
||||
vi.mock('../../lib/store/settingsStore',()=>({useSettingsStore:Object.assign((fn:(s:unknown)=>unknown)=>fn({getText:()=>''}),{getState:()=>({getText:()=>''})})}));
|
||||
vi.mock('../SafeImage',()=>({default:({alt}:{alt:string})=><img alt={alt}/>}));
|
||||
const products=[{id:'1',name:'کلسیم',artNo:'A1',category:'مفاصل',categorySlug:'joints',image:'/x.png',symptoms:[],main_ingredients:['Calcium']},{id:'2',name:'Other supplement',artNo:'B2',category:'unknown',image:'/y.png',symptoms:[],main_ingredients:[]}] as unknown as Product[];
|
||||
beforeEach(()=>{vi.useFakeTimers();Object.defineProperty(window,'innerWidth',{configurable:true,value:1024});push.mockClear();});
|
||||
afterEach(()=>{cleanup();vi.useRealTimers();vi.restoreAllMocks();});
|
||||
const search=()=>screen.getByPlaceholderText('جستجوی نام مکمل، کد کالا، ترکیبات...');
|
||||
it('guards cover and repeated flips during transition',()=>{render(<FlipbookCatalog products={products}/>);expect(screen.getByRole('button',{name:'صفحه قبلی'})).toBeDisabled();fireEvent.click(screen.getByRole('button',{name:'صفحه بعدی'}));expect(screen.getByRole('button',{name:'صفحه بعدی'})).toBeDisabled();act(()=>vi.advanceTimersByTime(650));expect(screen.getByRole('button',{name:'صفحه قبلی'})).not.toBeDisabled();fireEvent.keyDown(window,{key:'ArrowRight'});act(()=>vi.advanceTimersByTime(650));expect(screen.getByRole('button',{name:'صفحه قبلی'})).toBeDisabled();});
|
||||
it.each(['كلسيم','Calcium','B2'])('searches normalized names, ingredients, unmatched codes: %s',query=>{render(<FlipbookCatalog products={products}/>);fireEvent.change(search(),{target:{value:query}});const result=screen.getByText(query==='B2'?'Other supplement':'کلسیم',{selector:'span.truncate'});fireEvent.click(result);expect(search()).toHaveValue('');});
|
||||
it('ignores navigation keys while search focused',()=>{render(<FlipbookCatalog products={products}/>);search().focus();fireEvent.keyDown(window,{key:'ArrowLeft'});act(()=>vi.advanceTimersByTime(1000));expect(screen.getByRole('button',{name:'صفحه قبلی'})).toBeDisabled();});
|
||||
it('reports no results then jumps with Enter',()=>{render(<FlipbookCatalog products={products}/>);fireEvent.change(search(),{target:{value:'not-found'}});expect(screen.getByText(/یافت نشد/)).toBeInTheDocument();fireEvent.change(search(),{target:{value:'A1'}});fireEvent.keyDown(search(),{key:'Enter'});expect(search()).toHaveValue('');expect(screen.getByRole('button',{name:'صفحه قبلی'})).not.toBeDisabled();});
|
||||
it('prints and returns home',()=>{vi.spyOn(window,'print').mockImplementation(()=>{});render(<FlipbookCatalog products={[]}/>);fireEvent.click(screen.getByTitle('دانلود یا چاپ نسخه کامل PDF کاتالوگ (تمامی محصولات)'));expect(window.print).toHaveBeenCalledOnce();fireEvent.click(screen.getByText('بازگشت'));expect(push).toHaveBeenCalledWith('/');});
|
||||
it('responds to horizontal not vertical mobile swipes',()=>{Object.defineProperty(window,'innerWidth',{configurable:true,value:400});const {container}=render(<FlipbookCatalog products={products}/>);const root=container.firstChild!;fireEvent.touchStart(root,{touches:[{clientX:0,clientY:0}]});fireEvent.touchEnd(root,{changedTouches:[{clientX:10,clientY:100}]});act(()=>vi.advanceTimersByTime(350));expect(screen.getByRole('button',{name:'صفحه قبلی'})).toBeDisabled();fireEvent.touchStart(root,{touches:[{clientX:0,clientY:0}]});fireEvent.touchEnd(root,{changedTouches:[{clientX:100,clientY:10}]});act(()=>vi.advanceTimersByTime(350));expect(screen.getByRole('button',{name:'صفحه قبلی'})).not.toBeDisabled();});
|
||||
@@ -54,8 +54,8 @@ describe('Header', () => {
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Canina')).toBeInTheDocument();
|
||||
expect(screen.getByText('ایران')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('Canina')[0]).toBeInTheDocument();
|
||||
expect(screen.getAllByText('ایران')[0]).toBeInTheDocument();
|
||||
expect(screen.getByText('ورود / ثبتنام')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import HeaderButton from '../HeaderButton';
|
||||
|
||||
vi.mock('motion/react', () => ({
|
||||
motion: {
|
||||
button: ({ children, className, onClick }: any) => (
|
||||
<button className={className} onClick={onClick}>
|
||||
{children}
|
||||
</button>
|
||||
),
|
||||
div: ({ children, className }: any) => (
|
||||
<div className={className}>{children}</div>
|
||||
),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('HeaderButton Component', () => {
|
||||
it('renders children and responds to click event', () => {
|
||||
const handleClick = vi.fn();
|
||||
render(
|
||||
<HeaderButton onClick={handleClick} variant="primary">
|
||||
سبد خرید
|
||||
</HeaderButton>,
|
||||
);
|
||||
|
||||
const btn = screen.getByText('سبد خرید');
|
||||
expect(btn).toBeInTheDocument();
|
||||
fireEvent.click(btn);
|
||||
expect(handleClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('renders badge with Persian numerals after mounting', async () => {
|
||||
render(
|
||||
<HeaderButton badge={3}>
|
||||
اعلانها
|
||||
</HeaderButton>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
// 3 converted to Persian is ۳
|
||||
expect(screen.getByText('۳')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('does not render badge if badge count is 0', async () => {
|
||||
render(
|
||||
<HeaderButton badge={0}>
|
||||
پیامها
|
||||
</HeaderButton>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText('۰')).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,220 @@
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import IngredientWiki from '../IngredientWiki';
|
||||
import api from '../../lib/services/api';
|
||||
import { productService } from '../../lib/services/productService';
|
||||
|
||||
const mockPush = vi.fn();
|
||||
const mockSearchParamsGet = vi.fn();
|
||||
|
||||
// Mock next/navigation
|
||||
vi.mock('next/navigation', () => ({
|
||||
useRouter: () => ({
|
||||
push: mockPush,
|
||||
}),
|
||||
useSearchParams: () => ({
|
||||
get: mockSearchParamsGet,
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock motion/react
|
||||
vi.mock('motion/react', () => ({
|
||||
motion: {
|
||||
div: ({ children, className, ...props }: any) => <div className={className} {...props}>{children}</div>,
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock next/image
|
||||
vi.mock('next/image', () => ({
|
||||
default: ({ src, alt, className }: any) => <img src={src} alt={alt} className={className} data-testid="next-image" />,
|
||||
}));
|
||||
|
||||
// Mock next/link
|
||||
vi.mock('next/link', () => ({
|
||||
default: ({ children, href, className }: any) => (
|
||||
<a href={href} className={className}>
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
}));
|
||||
|
||||
// Mock productService and api
|
||||
vi.mock('../../lib/services/productService', () => ({
|
||||
productService: {
|
||||
getProducts: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../lib/services/api', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('IngredientWiki Component', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockSearchParamsGet.mockReturnValue(null);
|
||||
});
|
||||
|
||||
it('renders default static wiki content when api call fails or returns empty', async () => {
|
||||
(productService.getProducts as any).mockRejectedValueOnce(new Error('fail'));
|
||||
(api.get as any).mockRejectedValueOnce(new Error('fail'));
|
||||
|
||||
render(<IngredientWiki />);
|
||||
|
||||
// Main header check using role heading or getAllByText
|
||||
const titles = screen.getAllByText(/دانشنامه مواد/);
|
||||
expect(titles.length).toBeGreaterThanOrEqual(1);
|
||||
expect(screen.getByText('علم در خدمت کیفیت')).toBeInTheDocument();
|
||||
expect(screen.getByText(/۱۰۰٪ فاقد قند افزوده/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/مطابق استانداردهای دارویی و بالینی آلمان/)).toBeInTheDocument();
|
||||
|
||||
// Default static wiki ingredient should be rendered (e.g. green-mussel / صدف لبسبز)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/صدف لبسبز/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('renders ingredients fetched from API and connects products correctly', async () => {
|
||||
const mockIngredientsFromApi = [
|
||||
{
|
||||
id: 'biotin',
|
||||
slug: 'biotin',
|
||||
nameFa: 'بیوتین',
|
||||
scientificName: 'Vitamin H',
|
||||
description: 'ویتامین ضروری برای سلامت پوست و موی حیوانات خانگی.',
|
||||
benefits: ['کاهش ریزش مو', 'تقویت بافت شاخی پنجه'],
|
||||
},
|
||||
{
|
||||
id: 'salmon-oil',
|
||||
slug: 'salmon-oil',
|
||||
nameFa: 'روغن سالمون وحشی',
|
||||
nameEn: 'Wild Salmon Oil',
|
||||
description: 'منبع غنی اسیدهای چرب امگا ۳ و امگا ۶.',
|
||||
benefits: ['سلامت قلب و عروق', 'درخشندگی پوست'],
|
||||
},
|
||||
];
|
||||
|
||||
const mockProductsFromApi = [
|
||||
{
|
||||
id: 'p-1',
|
||||
slug: 'biotin-tabs',
|
||||
name: 'قرص بیوتین قوی سگ و گربه',
|
||||
main_ingredients: ['بیوتین', 'مخمر'],
|
||||
benefitsList: ['جلوگیری از کچلی و ریزش'],
|
||||
image: '/images/biotin-tabs.png',
|
||||
},
|
||||
{
|
||||
id: 'p-2',
|
||||
slug: 'salmon-oil-bottle',
|
||||
name: 'روغن ماهی سالمون خالص',
|
||||
main_ingredients: ['سالمون'],
|
||||
image: '/images/salmon.png',
|
||||
},
|
||||
];
|
||||
|
||||
(api.get as any).mockResolvedValueOnce({ data: mockIngredientsFromApi });
|
||||
(productService.getProducts as any).mockResolvedValueOnce({ data: mockProductsFromApi });
|
||||
|
||||
render(<IngredientWiki />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/بیوتین \(Vitamin H\)/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByText('ویتامین ضروری برای سلامت پوست و موی حیوانات خانگی.')).toBeInTheDocument();
|
||||
expect(screen.getByText('کاهش ریزش مو')).toBeInTheDocument();
|
||||
expect(screen.getByText('تقویت بافت شاخی پنجه')).toBeInTheDocument();
|
||||
|
||||
// Check linked products
|
||||
expect(screen.getByText('قرص بیوتین قوی سگ و گربه')).toBeInTheDocument();
|
||||
expect(screen.getByText('روغن ماهی سالمون خالص')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('filters ingredients through search query input', async () => {
|
||||
(productService.getProducts as any).mockResolvedValueOnce({ data: [] });
|
||||
(api.get as any).mockResolvedValueOnce({
|
||||
data: [
|
||||
{
|
||||
id: 'collagen',
|
||||
slug: 'collagen',
|
||||
nameFa: 'کلاژن هیدرولیز شده',
|
||||
description: 'پروتئین ساختاری مفاصل و غضروفها.',
|
||||
benefits: ['انعطاف مفاصل'],
|
||||
},
|
||||
{
|
||||
id: 'silver',
|
||||
slug: 'silver',
|
||||
nameFa: 'میکروسیلور',
|
||||
description: 'نقره ضد باکتری برای مراقبت از لثه و دندان.',
|
||||
benefits: ['کاهش جرم دندان'],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
render(<IngredientWiki />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('کلاژن هیدرولیز شده')).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getByText('میکروسیلور')).toBeInTheDocument();
|
||||
|
||||
// Type "کلاژن" into search box
|
||||
const searchInput = screen.getByPlaceholderText(/جستجوی ماده مؤثره/);
|
||||
fireEvent.change(searchInput, { target: { value: 'کلاژن' } });
|
||||
|
||||
expect(screen.getByText('کلاژن هیدرولیز شده')).toBeInTheDocument();
|
||||
expect(screen.queryByText('میکروسیلور')).not.toBeInTheDocument();
|
||||
|
||||
// Search something that does not exist
|
||||
fireEvent.change(searchInput, { target: { value: 'ماده ناموجود ۱۲۳' } });
|
||||
expect(screen.getByText('مادهای یافت نشد')).toBeInTheDocument();
|
||||
expect(screen.getByText('با عبارت جستجو شده ماده مؤثرهای مطابقت ندارد.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('navigates when back button or breadcrumb is clicked', () => {
|
||||
(productService.getProducts as any).mockResolvedValueOnce({ data: [] });
|
||||
(api.get as any).mockResolvedValueOnce({ data: [] });
|
||||
|
||||
render(<IngredientWiki />);
|
||||
|
||||
const backButton = screen.getByRole('button', { name: /بازگشت/ });
|
||||
fireEvent.click(backButton);
|
||||
expect(mockPush).toHaveBeenCalledWith('/');
|
||||
|
||||
const homeCrumb = screen.getByText('خانه');
|
||||
fireEvent.click(homeCrumb);
|
||||
expect(mockPush).toHaveBeenCalledWith('/');
|
||||
});
|
||||
|
||||
it('handles termParam query string to scroll to specific ingredient', async () => {
|
||||
mockSearchParamsGet.mockImplementation((param: string) => {
|
||||
if (param === 'term') return 'colostrum';
|
||||
return null;
|
||||
});
|
||||
|
||||
const mockScrollTo = vi.fn();
|
||||
window.scrollTo = mockScrollTo;
|
||||
|
||||
(productService.getProducts as any).mockResolvedValueOnce({ data: [] });
|
||||
(api.get as any).mockResolvedValueOnce({
|
||||
data: [
|
||||
{
|
||||
id: 'colostrum',
|
||||
slug: 'colostrum',
|
||||
nameFa: 'آغوز گاو (Colostrum)',
|
||||
description: 'تقویت کننده سیستم ایمنی',
|
||||
benefits: ['حاوی آنتی بادی'],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
render(<IngredientWiki />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/آغوز گاو/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,229 @@
|
||||
"use client";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import LoginModal from "../LoginModal";
|
||||
import { authService } from "../../lib/services/authService";
|
||||
import { useUserStore } from "../../lib/store/userStore";
|
||||
import { toast } from "sonner";
|
||||
|
||||
vi.mock("../../lib/services/authService", () => ({
|
||||
authService: {
|
||||
sendOtp: vi.fn(),
|
||||
verifyOtp: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/store/userStore", () => ({
|
||||
useUserStore: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("sonner", () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock OtpInput5
|
||||
vi.mock("../OtpInput5", () => ({
|
||||
default: ({
|
||||
value,
|
||||
onChange,
|
||||
onComplete,
|
||||
disabled,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (val: string) => void;
|
||||
onComplete?: (code: string) => void;
|
||||
disabled?: boolean;
|
||||
}) => (
|
||||
<div data-testid="otp-input-container">
|
||||
<input
|
||||
data-testid="mock-otp-input"
|
||||
type="text"
|
||||
maxLength={5}
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
onChange(val);
|
||||
if (val.length === 5 && onComplete) {
|
||||
onComplete(val);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
describe("LoginModal Component", () => {
|
||||
const mockOnClose = vi.fn();
|
||||
const mockOnLogin = vi.fn();
|
||||
const mockFetchProfile = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
vi.mocked(useUserStore).mockReturnValue({
|
||||
fetchProfile: mockFetchProfile,
|
||||
isLoggedIn: false,
|
||||
} as any);
|
||||
});
|
||||
|
||||
it("does not render when isOpen is false", () => {
|
||||
const { container } = render(
|
||||
<LoginModal isOpen={false} onClose={mockOnClose} onLogin={mockOnLogin} />
|
||||
);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it("renders phone input step initially", () => {
|
||||
render(
|
||||
<LoginModal isOpen={true} onClose={mockOnClose} onLogin={mockOnLogin} />
|
||||
);
|
||||
|
||||
expect(screen.getByText("ورود به کنینا")).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText("مثال: ۰۹۱۲۳۴۵۶۷۸۹")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: /ارسال کد تایید/ })).toBeDisabled();
|
||||
});
|
||||
|
||||
it("validates mobile number prefix and length (09xxxxxxxxx)", async () => {
|
||||
render(
|
||||
<LoginModal isOpen={true} onClose={mockOnClose} onLogin={mockOnLogin} />
|
||||
);
|
||||
|
||||
const input = screen.getByPlaceholderText("مثال: ۰۹۱۲۳۴۵۶۷۸۹");
|
||||
fireEvent.change(input, { target: { value: "02112345678" } });
|
||||
|
||||
const submitBtn = screen.getByRole("button", { name: /ارسال کد تایید/ });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
expect(toast.error).toHaveBeenCalledWith(
|
||||
"شماره موبایل باید با ۰۹ شروع شده و ۱۱ رقم باشد"
|
||||
);
|
||||
expect(authService.sendOtp).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("sends OTP and transitions to OTP verification step", async () => {
|
||||
vi.mocked(authService.sendOtp).mockResolvedValueOnce({
|
||||
success: true,
|
||||
message: "کد ارسال شد",
|
||||
} as any);
|
||||
|
||||
render(
|
||||
<LoginModal isOpen={true} onClose={mockOnClose} onLogin={mockOnLogin} />
|
||||
);
|
||||
|
||||
const input = screen.getByPlaceholderText("مثال: ۰۹۱۲۳۴۵۶۷۸۹");
|
||||
fireEvent.change(input, { target: { value: "09129998877" } });
|
||||
|
||||
const submitBtn = screen.getByRole("button", { name: /ارسال کد تایید/ });
|
||||
expect(submitBtn).not.toBeDisabled();
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(authService.sendOtp).toHaveBeenCalledWith("09129998877");
|
||||
expect(toast.success).toHaveBeenCalledWith("کد تایید پیامک شد");
|
||||
expect(screen.getByTestId("otp-input-container")).toBeInTheDocument();
|
||||
expect(screen.getByText("کد تایید پیامکی")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("allows switching back to phone step via 'ویرایش شماره'", async () => {
|
||||
vi.mocked(authService.sendOtp).mockResolvedValueOnce({ success: true } as any);
|
||||
|
||||
render(
|
||||
<LoginModal isOpen={true} onClose={mockOnClose} onLogin={mockOnLogin} />
|
||||
);
|
||||
|
||||
const input = screen.getByPlaceholderText("مثال: ۰۹۱۲۳۴۵۶۷۸۹");
|
||||
fireEvent.change(input, { target: { value: "09129998877" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: /ارسال کد تایید/ }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("ویرایش شماره")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByText("ویرایش شماره"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByPlaceholderText("مثال: ۰۹۱۲۳۴۵۶۷۸۹")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("completes OTP verification and invokes onLogin and onClose on success", async () => {
|
||||
vi.mocked(authService.sendOtp).mockResolvedValueOnce({ success: true } as any);
|
||||
vi.mocked(authService.verifyOtp).mockResolvedValueOnce({
|
||||
success: true,
|
||||
token: "jwt-token-123",
|
||||
} as any);
|
||||
|
||||
render(
|
||||
<LoginModal isOpen={true} onClose={mockOnClose} onLogin={mockOnLogin} />
|
||||
);
|
||||
|
||||
const input = screen.getByPlaceholderText("مثال: ۰۹۱۲۳۴۵۶۷۸۹");
|
||||
fireEvent.change(input, { target: { value: "09129998877" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: /ارسال کد تایید/ }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("mock-otp-input")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const otpInput = screen.getByTestId("mock-otp-input");
|
||||
fireEvent.change(otpInput, { target: { value: "12345" } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(authService.verifyOtp).toHaveBeenCalledWith("09129998877", "12345");
|
||||
expect(mockFetchProfile).toHaveBeenCalled();
|
||||
expect(toast.success).toHaveBeenCalledWith("ورود با موفقیت انجام شد");
|
||||
expect(mockOnLogin).toHaveBeenCalled();
|
||||
expect(mockOnClose).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it("handles OTP verification error gracefully", async () => {
|
||||
vi.mocked(authService.sendOtp).mockResolvedValueOnce({ success: true } as any);
|
||||
vi.mocked(authService.verifyOtp).mockRejectedValueOnce({
|
||||
message: "کد وارد شده منقضی شده است",
|
||||
});
|
||||
|
||||
render(
|
||||
<LoginModal isOpen={true} onClose={mockOnClose} onLogin={mockOnLogin} />
|
||||
);
|
||||
|
||||
const input = screen.getByPlaceholderText("مثال: ۰۹۱۲۳۴۵۶۷۸۹");
|
||||
fireEvent.change(input, { target: { value: "09129998877" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: /ارسال کد تایید/ }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("mock-otp-input")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const otpInput = screen.getByTestId("mock-otp-input");
|
||||
fireEvent.change(otpInput, { target: { value: "99999" } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(authService.verifyOtp).toHaveBeenCalledWith("09129998877", "99999");
|
||||
expect(toast.error).toHaveBeenCalledWith("کد وارد شده منقضی شده است");
|
||||
expect(mockOnLogin).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it("renders pet contextual message when isAdvisorContext is true", () => {
|
||||
render(
|
||||
<LoginModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
onLogin={mockOnLogin}
|
||||
isAdvisorContext={true}
|
||||
petName="ژوپیتر"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText("ژوپیتر")).toBeInTheDocument();
|
||||
expect(screen.getByText(/رژیم مکمل پیشنهادی/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import MaintenancePage from '../MaintenancePage';
|
||||
import { useSettingsStore } from '../../lib/store/settingsStore';
|
||||
|
||||
// Mock BrandLogo
|
||||
vi.mock('../BrandLogo', () => ({
|
||||
default: ({ isDarkBackground, size }: { isDarkBackground?: boolean; size?: string }) => (
|
||||
<div data-testid="brand-logo" data-dark={isDarkBackground} data-size={size}>
|
||||
Canina Brand Logo
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
describe('MaintenancePage Component', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
useSettingsStore.setState({ texts: {} });
|
||||
});
|
||||
|
||||
it('renders default maintenance texts, logo, and German pharma footer', () => {
|
||||
render(<MaintenancePage />);
|
||||
|
||||
expect(screen.getByTestId('brand-logo')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('brand-logo')).toHaveAttribute('data-dark', 'true');
|
||||
expect(screen.getByTestId('brand-logo')).toHaveAttribute('data-size', 'lg');
|
||||
|
||||
expect(
|
||||
screen.getByText('سامانه در حال بهروزرسانی و ارتقای فنی است')
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText('سامانه در حال بهروزرسانی و ارتقا')
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText(/وبسایت رسمی کنینا ایران جهت ارتقای زیرساختها/)
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText('زمان تقریبی بازگشایی: کمتر از ۲ ساعت آینده')
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText('CANINA PHARMA GMBH GERMANY — نماینده رسمی ایران')
|
||||
).toBeInTheDocument();
|
||||
|
||||
const emergencyButton = screen.getByRole('link', { name: /پشتیبانی اضطراری/ });
|
||||
expect(emergencyButton).toBeInTheDocument();
|
||||
expect(emergencyButton).toHaveAttribute('href', 'tel:02188884444');
|
||||
});
|
||||
|
||||
it('renders custom maintenance messages and phone number from settings store texts', () => {
|
||||
useSettingsStore.setState({
|
||||
texts: {
|
||||
maintenance_title: 'سامانه موقتاً در دسترس نیست',
|
||||
maintenance_desc: 'در حال ارتقای سرورهای اصلی هستیم و تا دقایقی دیگر بازمیگردیم.',
|
||||
maintenance_badge: 'تعمیرات دورهای سرور',
|
||||
maintenance_eta: 'زمان بازگشایی: رأس ساعت ۱۸:۰۰',
|
||||
contact_phone: '021-22334455',
|
||||
},
|
||||
});
|
||||
|
||||
render(<MaintenancePage />);
|
||||
|
||||
expect(screen.getByText('سامانه موقتاً در دسترس نیست')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText('در حال ارتقای سرورهای اصلی هستیم و تا دقایقی دیگر بازمیگردیم.')
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText('تعمیرات دورهای سرور')).toBeInTheDocument();
|
||||
expect(screen.getByText('زمان بازگشایی: رأس ساعت ۱۸:۰۰')).toBeInTheDocument();
|
||||
|
||||
const emergencyButton = screen.getByRole('link', { name: /پشتیبانی اضطراری/ });
|
||||
expect(emergencyButton).toHaveAttribute('href', 'tel:02122334455');
|
||||
});
|
||||
|
||||
it('respects contact_phone_link override when provided in settings texts', () => {
|
||||
useSettingsStore.setState({
|
||||
texts: {
|
||||
contact_phone: '09120000000',
|
||||
contact_phone_link: 'tel:+989120000000',
|
||||
},
|
||||
});
|
||||
|
||||
render(<MaintenancePage />);
|
||||
|
||||
const emergencyButton = screen.getByRole('link', { name: /پشتیبانی اضطراری/ });
|
||||
expect(emergencyButton).toHaveAttribute('href', 'tel:+989120000000');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,196 @@
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import MobileBottomNav from '../MobileBottomNav';
|
||||
import { usePathname, useRouter } from 'next/navigation';
|
||||
import { useCartStore } from '../../lib/store/cartStore';
|
||||
import { useUserStore } from '../../lib/store/userStore';
|
||||
import { useUIStore } from '../../lib/store/uiStore';
|
||||
import { useSettingsStore } from '../../lib/store/settingsStore';
|
||||
import { useCatalogMode } from '../../lib/useCatalogMode';
|
||||
|
||||
vi.mock('next/navigation', () => ({
|
||||
usePathname: vi.fn(),
|
||||
useRouter: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../lib/store/cartStore', () => ({
|
||||
useCartStore: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../lib/store/userStore', () => ({
|
||||
useUserStore: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../lib/store/uiStore', () => ({
|
||||
useUIStore: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../lib/store/settingsStore', () => ({
|
||||
useSettingsStore: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../lib/useCatalogMode', () => ({
|
||||
useCatalogMode: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('MobileBottomNav Component', () => {
|
||||
const mockRouterPush = vi.fn();
|
||||
const mockSetAuthModalOpen = vi.fn();
|
||||
const mockSetCartOpen = vi.fn();
|
||||
const mockSetB2BPortalOpen = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
vi.mocked(usePathname).mockReturnValue('/');
|
||||
vi.mocked(useRouter).mockReturnValue({
|
||||
push: mockRouterPush,
|
||||
replace: vi.fn(),
|
||||
prefetch: vi.fn(),
|
||||
back: vi.fn(),
|
||||
} as any);
|
||||
|
||||
vi.mocked(useCartStore).mockReturnValue({
|
||||
getTotalItems: vi.fn().mockReturnValue(0),
|
||||
} as any);
|
||||
|
||||
vi.mocked(useUserStore).mockReturnValue({
|
||||
isLoggedIn: false,
|
||||
setAuthModalOpen: mockSetAuthModalOpen,
|
||||
} as any);
|
||||
|
||||
vi.mocked(useUIStore).mockImplementation((selector: any) => {
|
||||
const state = {
|
||||
setCartOpen: mockSetCartOpen,
|
||||
setB2BPortalOpen: mockSetB2BPortalOpen,
|
||||
};
|
||||
return selector(state);
|
||||
});
|
||||
|
||||
vi.mocked(useSettingsStore).mockImplementation((selector: any) => {
|
||||
const state = {
|
||||
getBoolean: vi.fn().mockReturnValue(true),
|
||||
getText: vi.fn().mockReturnValue('true'),
|
||||
};
|
||||
return selector(state);
|
||||
});
|
||||
|
||||
vi.mocked(useCatalogMode).mockReturnValue({
|
||||
isCatalogOnly: false,
|
||||
allowCart: true,
|
||||
} as any);
|
||||
});
|
||||
|
||||
it('renders all default 5 navigation tabs', () => {
|
||||
render(<MobileBottomNav />);
|
||||
|
||||
expect(screen.getByText('خانه')).toBeInTheDocument();
|
||||
expect(screen.getByText('منو')).toBeInTheDocument();
|
||||
expect(screen.getByText('فروشگاه')).toBeInTheDocument();
|
||||
expect(screen.getByText('سبد خرید')).toBeInTheDocument();
|
||||
expect(screen.getByText('حساب من')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides component on product detail page (/shop/[id])', () => {
|
||||
vi.mocked(usePathname).mockReturnValue('/shop/canina-glucosamine-123');
|
||||
const { container } = render(<MobileBottomNav />);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('highlights the active tab according to current path', () => {
|
||||
vi.mocked(usePathname).mockReturnValue('/');
|
||||
render(<MobileBottomNav />);
|
||||
|
||||
const homeLink = screen.getByText('خانه').closest('a');
|
||||
expect(homeLink).toHaveClass('text-canina-blue');
|
||||
expect(homeLink).toHaveClass('font-black');
|
||||
});
|
||||
|
||||
it('displays cart item badge with Persian formatted count when cart has items', () => {
|
||||
vi.mocked(useCartStore).mockReturnValue({
|
||||
getTotalItems: vi.fn().mockReturnValue(3),
|
||||
} as any);
|
||||
|
||||
render(<MobileBottomNav />);
|
||||
|
||||
// 3 in Persian is ۳
|
||||
expect(screen.getByText('۳')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens cart drawer when cart tab is clicked', () => {
|
||||
render(<MobileBottomNav />);
|
||||
|
||||
const cartBtn = screen.getByText('سبد خرید').closest('button');
|
||||
expect(cartBtn).toBeInTheDocument();
|
||||
fireEvent.click(cartBtn!);
|
||||
|
||||
expect(mockSetCartOpen).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('hides cart tab when catalog mode disables cart', () => {
|
||||
vi.mocked(useCatalogMode).mockReturnValue({
|
||||
isCatalogOnly: true,
|
||||
allowCart: false,
|
||||
} as any);
|
||||
|
||||
render(<MobileBottomNav />);
|
||||
|
||||
expect(screen.queryByText('سبد خرید')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('triggers auth modal when clicking account tab while not logged in', () => {
|
||||
vi.mocked(useUserStore).mockReturnValue({
|
||||
isLoggedIn: false,
|
||||
setAuthModalOpen: mockSetAuthModalOpen,
|
||||
} as any);
|
||||
|
||||
render(<MobileBottomNav />);
|
||||
|
||||
const accountBtn = screen.getByText('حساب من').closest('button');
|
||||
expect(accountBtn).toBeInTheDocument();
|
||||
fireEvent.click(accountBtn!);
|
||||
|
||||
expect(mockSetAuthModalOpen).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('navigates to /dashboard when clicking account tab while logged in', () => {
|
||||
vi.mocked(useUserStore).mockReturnValue({
|
||||
isLoggedIn: true,
|
||||
setAuthModalOpen: mockSetAuthModalOpen,
|
||||
} as any);
|
||||
|
||||
render(<MobileBottomNav />);
|
||||
|
||||
const accountBtn = screen.getByText('حساب من').closest('button');
|
||||
expect(accountBtn).toBeInTheDocument();
|
||||
fireEvent.click(accountBtn!);
|
||||
|
||||
expect(mockRouterPush).toHaveBeenCalledWith('/dashboard');
|
||||
});
|
||||
|
||||
it('opens shop bottom sheet when shop tab is clicked', () => {
|
||||
render(<MobileBottomNav />);
|
||||
|
||||
const shopBtn = screen.getByText('فروشگاه').closest('button');
|
||||
expect(shopBtn).toBeInTheDocument();
|
||||
fireEvent.click(shopBtn!);
|
||||
|
||||
// Sheet displays shop navigation elements
|
||||
expect(screen.getByPlaceholderText(/جستجوی دارو، ترکیب یا علامت بالینی/i)).toBeInTheDocument();
|
||||
expect(screen.getByText('مشاهده کاتالوگ و همه محصولات')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens menu bottom sheet when menu tab is clicked', () => {
|
||||
render(<MobileBottomNav />);
|
||||
|
||||
const menuBtn = screen.getByText('منو').closest('button');
|
||||
expect(menuBtn).toBeInTheDocument();
|
||||
fireEvent.click(menuBtn!);
|
||||
|
||||
expect(screen.getByText('دانشنامه علمی')).toBeInTheDocument();
|
||||
expect(screen.getByText('مجله سلامت پت')).toBeInTheDocument();
|
||||
expect(screen.getByText('ویدیوهای بالینی')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,170 @@
|
||||
import React from "react";
|
||||
import Link from "next/link";
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { render, screen, fireEvent, act } from "@testing-library/react";
|
||||
import NavigationProgressBar from "../NavigationProgressBar";
|
||||
|
||||
let mockPathname = "/";
|
||||
let mockSearchParams = new URLSearchParams();
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
usePathname: () => mockPathname,
|
||||
useSearchParams: () => mockSearchParams,
|
||||
}));
|
||||
|
||||
describe("NavigationProgressBar Component", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
mockPathname = "/";
|
||||
mockSearchParams = new URLSearchParams();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllTimers();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("initially does not render anything when progress is 0 and invisible", () => {
|
||||
const { container } = render(<NavigationProgressBar />);
|
||||
// On mount, completeProgress is triggered: progress = 100, then after 250ms visible=false, then after 200ms progress=0
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(500);
|
||||
});
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it("starts progress bar when clicking an internal link with different pathname", () => {
|
||||
const { container } = render(
|
||||
<div>
|
||||
<NavigationProgressBar />
|
||||
<Link href="/shop" data-testid="internal-link">
|
||||
فروشگاه
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
|
||||
// Settle initial completeProgress on mount
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(500);
|
||||
});
|
||||
expect(container.querySelector(".fixed")).toBeNull();
|
||||
|
||||
// Click internal link
|
||||
const link = screen.getByTestId("internal-link");
|
||||
act(() => {
|
||||
fireEvent.click(link);
|
||||
});
|
||||
|
||||
// Bar should now be visible with initial progress of 20%
|
||||
const barWrapper = container.querySelector(".fixed");
|
||||
expect(barWrapper).toBeInTheDocument();
|
||||
expect(barWrapper).toHaveStyle({ opacity: "1" });
|
||||
|
||||
const progressBar = barWrapper?.querySelector(".h-\\[3\\.5px\\]");
|
||||
expect(progressBar).toHaveStyle({ width: "20%" });
|
||||
|
||||
// Advance timer to trigger interval increments
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(300);
|
||||
});
|
||||
// Progress should have increased beyond 20%
|
||||
const currentWidth = parseFloat(progressBar?.getAttribute("style")?.match(/width:\s*([\d.]+)%/)?.[1] || "0");
|
||||
expect(currentWidth).toBeGreaterThan(20);
|
||||
});
|
||||
|
||||
it("ignores clicks on external, anchor, mailto, tel, and blank target links", () => {
|
||||
const { container } = render(
|
||||
<div>
|
||||
<NavigationProgressBar />
|
||||
<a href="#section" data-testid="hash-link">Hash</a>
|
||||
<a href="mailto:test@canina.ir" data-testid="mail-link">Mail</a>
|
||||
<a href="tel:02112345678" data-testid="tel-link">Tel</a>
|
||||
<a href="javascript:void(0)" data-testid="js-link">JS</a>
|
||||
<a href="/shop" target="_blank" data-testid="blank-link">New Tab</a>
|
||||
</div>
|
||||
);
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(500);
|
||||
});
|
||||
|
||||
// Click each link and assert progress bar remains not rendered
|
||||
["hash-link", "mail-link", "tel-link", "js-link", "blank-link"].forEach((id) => {
|
||||
act(() => {
|
||||
fireEvent.click(screen.getByTestId(id));
|
||||
});
|
||||
expect(container.querySelector(".fixed")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores clicks with modifier keys (ctrlKey, metaKey, shiftKey, altKey)", () => {
|
||||
const { container } = render(
|
||||
<div>
|
||||
<NavigationProgressBar />
|
||||
<Link href="/shop" data-testid="internal-link">فروشگاه</Link>
|
||||
</div>
|
||||
);
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(500);
|
||||
});
|
||||
|
||||
const link = screen.getByTestId("internal-link");
|
||||
act(() => {
|
||||
fireEvent.click(link, { ctrlKey: true });
|
||||
});
|
||||
expect(container.querySelector(".fixed")).toBeNull();
|
||||
|
||||
act(() => {
|
||||
fireEvent.click(link, { metaKey: true });
|
||||
});
|
||||
expect(container.querySelector(".fixed")).toBeNull();
|
||||
});
|
||||
|
||||
it("completes progress and hides when pathname or searchParams change", () => {
|
||||
const { container, rerender } = render(
|
||||
<div>
|
||||
<NavigationProgressBar />
|
||||
<Link href="/shop" data-testid="internal-link">فروشگاه</Link>
|
||||
</div>
|
||||
);
|
||||
|
||||
// Initial mount flush
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(500);
|
||||
});
|
||||
|
||||
// Start progress
|
||||
act(() => {
|
||||
fireEvent.click(screen.getByTestId("internal-link"));
|
||||
});
|
||||
|
||||
const barWrapper = container.querySelector(".fixed");
|
||||
expect(barWrapper).toBeInTheDocument();
|
||||
|
||||
// Route transition completes: pathname changes
|
||||
mockPathname = "/shop";
|
||||
rerender(
|
||||
<div>
|
||||
<NavigationProgressBar />
|
||||
<Link href="/shop" data-testid="internal-link">فروشگاه</Link>
|
||||
</div>
|
||||
);
|
||||
|
||||
// Progress moves to 100%
|
||||
const progressBar = container.querySelector(".h-\\[3\\.5px\\]");
|
||||
expect(progressBar).toHaveStyle({ width: "100%" });
|
||||
|
||||
// After 250ms opacity fades out (visible = false)
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(250);
|
||||
});
|
||||
expect(container.querySelector(".fixed")).toHaveStyle({ opacity: "0" });
|
||||
|
||||
// After another 200ms progress returns to 0 and bar unmounts
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200);
|
||||
});
|
||||
expect(container.querySelector(".fixed")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { render, screen, act } from '@testing-library/react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { NetworkBanner } from '../NetworkBanner';
|
||||
|
||||
let mockIsOnline = true;
|
||||
vi.mock('../../lib/hooks/useNetworkStatus', () => ({
|
||||
useNetworkStatus: () => mockIsOnline,
|
||||
}));
|
||||
|
||||
vi.mock('motion/react', () => ({
|
||||
motion: {
|
||||
div: ({ children, className }: any) => <div className={className}>{children}</div>,
|
||||
},
|
||||
AnimatePresence: ({ children }: any) => <>{children}</>,
|
||||
}));
|
||||
|
||||
describe('NetworkBanner Component', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
it('does not render banner when initially online', () => {
|
||||
mockIsOnline = true;
|
||||
render(<NetworkBanner />);
|
||||
expect(screen.queryByText(/اتصال اینترنت شما قطع شده است/)).toBeNull();
|
||||
});
|
||||
|
||||
it('renders offline warning when network goes offline', async () => {
|
||||
mockIsOnline = false;
|
||||
render(<NetworkBanner />);
|
||||
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
expect(screen.getByText(/اتصال اینترنت شما قطع شده است/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
"use client";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import OrderDetailsModal from "../OrderDetailsModal";
|
||||
|
||||
vi.mock("../lib/store/settingsStore", () => ({
|
||||
useSettingsStore: vi.fn((selector) =>
|
||||
selector({
|
||||
getText: vi.fn((key, def) => def),
|
||||
})
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("../lib/services/api", () => ({
|
||||
default: {
|
||||
post: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("sonner", () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("OrderDetailsModal Component", () => {
|
||||
const mockOrder = {
|
||||
id: "ord-998877",
|
||||
trackingNumber: "CN-TRACK-1234",
|
||||
status: "processing",
|
||||
date: "2026-10-10T12:00:00Z",
|
||||
total: 1250000,
|
||||
charityDonation: 50000,
|
||||
shippingAddress: {
|
||||
province: "تهران",
|
||||
city: "تهران",
|
||||
address: "میدان ونک، خیابان ملاصدرا",
|
||||
postalCode: "1994912345",
|
||||
phone: "09121112233",
|
||||
recipientName: "پرهام علوی",
|
||||
},
|
||||
items: [
|
||||
{
|
||||
id: "item-1",
|
||||
quantity: 2,
|
||||
priceValue: 600000,
|
||||
product: {
|
||||
nameFa: "مکمل مفاصل پتویتال",
|
||||
imageUrl: "/products/petvital.png",
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should render modal with order details when isOpen is true", () => {
|
||||
render(
|
||||
<OrderDetailsModal
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
order={mockOrder}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText(/جزئیات کامل سفارش/)).toBeInTheDocument();
|
||||
expect(screen.getByText("مکمل مفاصل پتویتال")).toBeInTheDocument();
|
||||
expect(screen.getByText("میدان ونک، خیابان ملاصدرا")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should not render when isOpen is false", () => {
|
||||
render(
|
||||
<OrderDetailsModal
|
||||
isOpen={false}
|
||||
onClose={vi.fn()}
|
||||
order={mockOrder}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.queryByText(/جزئیات کامل سفارش/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should call onClose when back button is clicked", () => {
|
||||
const handleClose = vi.fn();
|
||||
render(
|
||||
<OrderDetailsModal
|
||||
isOpen={true}
|
||||
onClose={handleClose}
|
||||
order={mockOrder}
|
||||
/>
|
||||
);
|
||||
|
||||
const backBtn = screen.getByRole("button", { name: "بازگشت" });
|
||||
fireEvent.click(backBtn);
|
||||
|
||||
expect(handleClose).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import OrderSuccess from '../OrderSuccess';
|
||||
|
||||
const mockPush = vi.fn();
|
||||
vi.mock('next/navigation', () => ({
|
||||
useRouter: () => ({
|
||||
push: mockPush,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('motion/react', () => ({
|
||||
motion: {
|
||||
div: ({ children, className }: any) => <div className={className}>{children}</div>,
|
||||
},
|
||||
}));
|
||||
|
||||
const mockOrders = [
|
||||
{
|
||||
id: 'ord-1234',
|
||||
items: [{ product: { id: 'canhydrox-gag' } }],
|
||||
isRefill: true,
|
||||
},
|
||||
];
|
||||
|
||||
const mockActivePet: any = { name: 'تدی' };
|
||||
|
||||
vi.mock('../../lib/store/cartStore', () => ({
|
||||
useCartStore: () => ({
|
||||
orders: mockOrders,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('../../lib/store/usePetStore', () => ({
|
||||
usePetStore: () => ({
|
||||
getActivePet: () => mockActivePet,
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('OrderSuccess Component', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders order confirmation details for valid order', () => {
|
||||
render(<OrderSuccess orderId="ord-1234" />);
|
||||
expect(screen.getByText('سفارش شما با موفقیت ثبت شد!')).toBeInTheDocument();
|
||||
expect(screen.getByText('ord-1234')).toBeInTheDocument();
|
||||
expect(screen.getAllByText(/تدی/)[0]).toBeInTheDocument();
|
||||
expect(screen.getByText(/Canhydrox/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/سرویس تمدید خودکار \(Refill\)/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('navigates to tracking page when track button is clicked', () => {
|
||||
render(<OrderSuccess orderId="ord-1234" />);
|
||||
const trackBtn = screen.getByText('مشاهده و پیگیری زنده سفارش');
|
||||
fireEvent.click(trackBtn);
|
||||
expect(mockPush).toHaveBeenCalledWith('/track');
|
||||
});
|
||||
|
||||
it('returns null if order is not found', () => {
|
||||
const { container } = render(<OrderSuccess orderId="non-existing-id" />);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
"use client";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import OrderTracking from "../OrderTracking";
|
||||
import { useCartStore } from "../../lib/store/cartStore";
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({
|
||||
push: vi.fn(),
|
||||
back: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/store/cartStore", () => ({
|
||||
useCartStore: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("OrderTracking Component", () => {
|
||||
const mockOrders = [
|
||||
{
|
||||
id: "ord-101",
|
||||
trackingNumber: "TRK-9988",
|
||||
date: "2026-10-10T12:00:00Z",
|
||||
status: "processing",
|
||||
total: 1500000,
|
||||
items: [
|
||||
{
|
||||
product: { name: "مکمل مفاصل سگ" },
|
||||
quantity: 2,
|
||||
},
|
||||
],
|
||||
shippingAddress: {
|
||||
province: "تهران",
|
||||
city: "تهران",
|
||||
detail: "خیابان ولیعصر پلاک ۱",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "ord-102",
|
||||
trackingNumber: "TRK-7766",
|
||||
date: "2026-10-11T12:00:00Z",
|
||||
status: "delivered",
|
||||
total: 850000,
|
||||
items: [
|
||||
{
|
||||
product: { name: "روغن سالمون" },
|
||||
quantity: 1,
|
||||
},
|
||||
],
|
||||
shippingAddress: {
|
||||
province: "اصفهان",
|
||||
city: "اصفهان",
|
||||
detail: "چهارباغ عباسی",
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should display the first order by default when orders exist", () => {
|
||||
vi.mocked(useCartStore).mockReturnValue({
|
||||
orders: mockOrders,
|
||||
} as any);
|
||||
|
||||
render(<OrderTracking />);
|
||||
|
||||
expect(screen.getByText("وضعیت لحظهای سفارش")).toBeInTheDocument();
|
||||
expect(screen.getByText("TRK-9988")).toBeInTheDocument();
|
||||
expect(screen.getByText("آمادهسازی در انبار")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should show empty state message if no orders exist", () => {
|
||||
vi.mocked(useCartStore).mockReturnValue({
|
||||
orders: [],
|
||||
} as any);
|
||||
|
||||
render(<OrderTracking />);
|
||||
|
||||
expect(
|
||||
screen.getByText(/سفارشی یافت نشد/)
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should find and display specific order when searched by tracking number", () => {
|
||||
vi.mocked(useCartStore).mockReturnValue({
|
||||
orders: mockOrders,
|
||||
} as any);
|
||||
|
||||
render(<OrderTracking />);
|
||||
|
||||
const searchInput = screen.getByPlaceholderText(
|
||||
"شماره سفارش (CN-XXXXX) یا کد رهگیری پستی را وارد کنید..."
|
||||
);
|
||||
const searchButton = screen.getByText("رهگیری آنی");
|
||||
|
||||
fireEvent.change(searchInput, { target: { value: "TRK-7766" } });
|
||||
fireEvent.click(searchButton);
|
||||
|
||||
expect(screen.getByText("TRK-7766")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should show empty order state if search query does not match any order", () => {
|
||||
vi.mocked(useCartStore).mockReturnValue({
|
||||
orders: mockOrders,
|
||||
} as any);
|
||||
|
||||
render(<OrderTracking />);
|
||||
|
||||
const searchInput = screen.getByPlaceholderText(
|
||||
"شماره سفارش (CN-XXXXX) یا کد رهگیری پستی را وارد کنید..."
|
||||
);
|
||||
const searchButton = screen.getByText("رهگیری آنی");
|
||||
|
||||
fireEvent.change(searchInput, { target: { value: "NON-EXISTENT" } });
|
||||
fireEvent.click(searchButton);
|
||||
|
||||
expect(
|
||||
screen.getByText(/سفارشی یافت نشد/)
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import OtpInput5 from '../OtpInput5';
|
||||
|
||||
describe('OtpInput5 Component', () => {
|
||||
it('renders 5 input boxes', () => {
|
||||
render(<OtpInput5 value="" onChange={vi.fn()} />);
|
||||
const inputs = screen.getAllByRole('textbox');
|
||||
expect(inputs).toHaveLength(5);
|
||||
});
|
||||
|
||||
it('updates digit and focuses next input on typing', () => {
|
||||
const handleChange = vi.fn();
|
||||
render(<OtpInput5 value="" onChange={handleChange} />);
|
||||
const inputs = screen.getAllByRole('textbox');
|
||||
|
||||
fireEvent.change(inputs[0], { target: { value: '4' } });
|
||||
expect(handleChange).toHaveBeenCalledWith('4');
|
||||
});
|
||||
|
||||
it('converts Persian digits automatically to English', () => {
|
||||
const handleChange = vi.fn();
|
||||
render(<OtpInput5 value="" onChange={handleChange} />);
|
||||
const inputs = screen.getAllByRole('textbox');
|
||||
|
||||
fireEvent.change(inputs[0], { target: { value: '۹' } });
|
||||
expect(handleChange).toHaveBeenCalledWith('9');
|
||||
});
|
||||
|
||||
it('distributes full 5-digit pasted code and calls onComplete', () => {
|
||||
const handleChange = vi.fn();
|
||||
const handleComplete = vi.fn();
|
||||
render(
|
||||
<OtpInput5
|
||||
value=""
|
||||
onChange={handleChange}
|
||||
onComplete={handleComplete}
|
||||
/>,
|
||||
);
|
||||
const inputs = screen.getAllByRole('textbox');
|
||||
|
||||
fireEvent.paste(inputs[0], {
|
||||
clipboardData: {
|
||||
getData: () => '12345',
|
||||
},
|
||||
});
|
||||
|
||||
expect(handleChange).toHaveBeenCalledWith('12345');
|
||||
expect(handleComplete).toHaveBeenCalledWith('12345');
|
||||
});
|
||||
|
||||
it('handles backspace to navigate to previous input when current is empty', () => {
|
||||
const handleChange = vi.fn();
|
||||
render(<OtpInput5 value="12" onChange={handleChange} />);
|
||||
const inputs = screen.getAllByRole('textbox');
|
||||
|
||||
fireEvent.keyDown(inputs[2], { key: 'Backspace' });
|
||||
expect(handleChange).toHaveBeenCalledWith('1');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,301 @@
|
||||
"use client";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import PetProfile from "../PetProfile";
|
||||
import { productService } from "../../lib/services/productService";
|
||||
import api from "../../lib/services/api";
|
||||
import { toast } from "sonner";
|
||||
|
||||
// Mock motion/react
|
||||
vi.mock("motion/react", () => ({
|
||||
AnimatePresence: ({ children }: { children: React.ReactNode }) => <>{children}</>,
|
||||
motion: {
|
||||
div: ({ children, ...props }: any) => <div {...props}>{children}</div>,
|
||||
article: ({ children, ...props }: any) => <article {...props}>{children}</article>,
|
||||
button: ({ children, ...props }: any) => <button {...props}>{children}</button>,
|
||||
},
|
||||
}));
|
||||
|
||||
// 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" />
|
||||
),
|
||||
}));
|
||||
|
||||
// Mock sonner toast
|
||||
vi.mock("sonner", () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock next/navigation
|
||||
const mockBack = vi.fn();
|
||||
const mockPush = vi.fn();
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({
|
||||
back: mockBack,
|
||||
push: mockPush,
|
||||
}),
|
||||
useSearchParams: () => new URLSearchParams(),
|
||||
}));
|
||||
|
||||
// Mock services
|
||||
vi.mock("../../lib/services/productService", () => ({
|
||||
productService: {
|
||||
getProducts: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/services/api", () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
},
|
||||
BASE_DOMAIN: "https://canina.ir",
|
||||
}));
|
||||
|
||||
// Mock stores
|
||||
const mockPets: any[] = [];
|
||||
let mockActivePet: any = null;
|
||||
const mockAddPet = vi.fn();
|
||||
const mockUpdatePet = vi.fn();
|
||||
const mockRemovePet = vi.fn();
|
||||
const mockSetActivePet = vi.fn();
|
||||
const mockAddReminder = vi.fn();
|
||||
const mockToggleReminder = vi.fn();
|
||||
const mockAddHealthLog = vi.fn();
|
||||
|
||||
vi.mock("../../lib/store/usePetStore", () => ({
|
||||
usePetStore: () => ({
|
||||
pets: mockPets,
|
||||
activePetId: mockActivePet?.id || null,
|
||||
getActivePet: () => mockActivePet,
|
||||
addPet: mockAddPet,
|
||||
updatePet: mockUpdatePet,
|
||||
removePet: mockRemovePet,
|
||||
setActivePet: mockSetActivePet,
|
||||
addReminder: mockAddReminder,
|
||||
toggleReminder: mockToggleReminder,
|
||||
addHealthLog: mockAddHealthLog,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/store/cartStore", () => ({
|
||||
useCartStore: () => ({
|
||||
orders: [],
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/store/settingsStore", () => ({
|
||||
useSettingsStore: () => true,
|
||||
}));
|
||||
|
||||
// Mock child components that are not under direct test
|
||||
vi.mock("../SmartAdvisor", () => ({
|
||||
default: () => <div data-testid="smart-advisor">SmartAdvisor Mock</div>,
|
||||
}));
|
||||
|
||||
vi.mock("../OrderDetailsModal", () => ({
|
||||
default: () => null,
|
||||
}));
|
||||
|
||||
describe("PetProfile Component", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockPets.length = 0;
|
||||
mockActivePet = null;
|
||||
vi.mocked(productService.getProducts).mockResolvedValue({ data: [] } as any);
|
||||
vi.mocked(api.get).mockResolvedValue({ data: [] });
|
||||
});
|
||||
|
||||
it("renders pet index view when pets list is displayed", async () => {
|
||||
const existingPet = {
|
||||
id: "pet-1",
|
||||
name: "لئو",
|
||||
type: "سگ",
|
||||
breed: "هاسکی",
|
||||
age: 2,
|
||||
weight: 24,
|
||||
activityLevel: "زیاد",
|
||||
medicalConditions: [],
|
||||
reminders: [],
|
||||
logs: [],
|
||||
};
|
||||
mockPets.push(existingPet);
|
||||
|
||||
render(<PetProfile initialView="index" />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("همدمهای من")).toBeInTheDocument();
|
||||
expect(screen.getByText("لئو")).toBeInTheDocument();
|
||||
expect(screen.getByText("هاسکی")).toBeInTheDocument();
|
||||
expect(screen.getByText("صدور شناسنامه جدید")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("handles multi-step pet creation wizard when pets exist", async () => {
|
||||
const existingPet = {
|
||||
id: "pet-1",
|
||||
name: "لئو",
|
||||
type: "سگ",
|
||||
breed: "هاسکی",
|
||||
age: 2,
|
||||
weight: 24,
|
||||
activityLevel: "زیاد",
|
||||
medicalConditions: [],
|
||||
};
|
||||
mockPets.push(existingPet);
|
||||
|
||||
render(<PetProfile initialView="add" />);
|
||||
|
||||
// Step 1: Name and Species
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("صدور شناسنامه سلامت")).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText("مثلاً: لوسی")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const nextBtn = screen.getByRole("button", { name: /گام بعدی/i });
|
||||
expect(nextBtn).toBeDisabled();
|
||||
|
||||
// Type pet name
|
||||
const nameInput = screen.getByPlaceholderText("مثلاً: لوسی");
|
||||
fireEvent.change(nameInput, { target: { value: "تدی" } });
|
||||
|
||||
// Choose cat species
|
||||
const catBtn = screen.getByRole("button", { name: "گربه" });
|
||||
fireEvent.click(catBtn);
|
||||
|
||||
// Type breed
|
||||
const breedInput = screen.getByPlaceholderText("آلمانی، پرشین، میکس و...");
|
||||
fireEvent.change(breedInput, { target: { value: "پرشین کلاسیک" } });
|
||||
|
||||
expect(nextBtn).not.toBeDisabled();
|
||||
fireEvent.click(nextBtn);
|
||||
|
||||
// Step 2: Age, Weight, Activity level
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("سطح فعالیت روزانه")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const ageInput = screen.getByPlaceholderText("۳");
|
||||
fireEvent.change(ageInput, { target: { value: "2" } });
|
||||
|
||||
const activityHighBtn = screen.getByRole("button", { name: "زیاد" });
|
||||
fireEvent.click(activityHighBtn);
|
||||
|
||||
const step2NextBtn = screen.getByRole("button", { name: /گام بعدی/i });
|
||||
fireEvent.click(step2NextBtn);
|
||||
|
||||
// Step 3: Medical history and submission
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("سوابق درمانی و موارد خاص")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Select hair loss condition
|
||||
const hairLossBtn = screen.getByText("ریزش موی شدید");
|
||||
fireEvent.click(hairLossBtn);
|
||||
|
||||
// Submit form
|
||||
const submitBtn = screen.getByRole("button", { name: /مشاهده پرونده سلامت/i });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
expect(mockAddPet).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
name: "تدی",
|
||||
type: "گربه",
|
||||
breed: "پرشین کلاسیک",
|
||||
age: 2,
|
||||
activityLevel: "زیاد",
|
||||
medicalConditions: ["ریزش موی شدید"],
|
||||
})
|
||||
);
|
||||
expect(toast.success).toHaveBeenCalledWith("شناسنامه جدید با موفقیت صادر شد");
|
||||
});
|
||||
|
||||
it("allows navigating back across steps in add mode", async () => {
|
||||
const existingPet = {
|
||||
id: "pet-1",
|
||||
name: "لئو",
|
||||
type: "سگ",
|
||||
breed: "هاسکی",
|
||||
age: 2,
|
||||
weight: 24,
|
||||
activityLevel: "زیاد",
|
||||
medicalConditions: [],
|
||||
};
|
||||
mockPets.push(existingPet);
|
||||
|
||||
render(<PetProfile initialView="add" />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByPlaceholderText("مثلاً: لوسی")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const nameInput = screen.getByPlaceholderText("مثلاً: لوسی");
|
||||
fireEvent.change(nameInput, { target: { value: "ببری" } });
|
||||
|
||||
const nextBtn = screen.getByRole("button", { name: /گام بعدی/i });
|
||||
fireEvent.click(nextBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("سطح فعالیت روزانه")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Click previous step
|
||||
const prevBtn = screen.getByRole("button", { name: /قبلی/i });
|
||||
fireEvent.click(prevBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByPlaceholderText("مثلاً: لوسی")).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue("ببری")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("renders pet detail view and handles deleting a pet via confirmation modal", async () => {
|
||||
const existingPet = {
|
||||
id: "pet-101",
|
||||
name: "ماکس",
|
||||
type: "سگ",
|
||||
breed: "ژرمن شپرد",
|
||||
age: 4,
|
||||
weight: 32,
|
||||
activityLevel: "زیاد",
|
||||
medicalConditions: ["جراحی مفاصل"],
|
||||
reminders: [],
|
||||
logs: [],
|
||||
consumptions: [],
|
||||
createdAt: "2026-01-01",
|
||||
};
|
||||
|
||||
mockPets.push(existingPet);
|
||||
mockActivePet = existingPet;
|
||||
|
||||
const { container } = render(<PetProfile initialView="index" />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("ماکس")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// In index card, delete button has class "text-medical-gray-300 hover:text-red-500"
|
||||
const trashBtn = container.querySelector("button.hover\\:text-red-500");
|
||||
expect(trashBtn).not.toBeNull();
|
||||
fireEvent.click(trashBtn!);
|
||||
|
||||
// Confirmation modal should open
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("حذف شناسنامه ماکس؟")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Click confirm delete
|
||||
const confirmDeleteBtn = screen.getByText("حذف نهایی");
|
||||
fireEvent.click(confirmDeleteBtn);
|
||||
|
||||
expect(mockRemovePet).toHaveBeenCalledWith("pet-101");
|
||||
expect(toast.error).toHaveBeenCalledWith("شناسنامه ماکس حذف شد");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import React from 'react';
|
||||
import {render,screen,fireEvent,waitFor,cleanup} from '@testing-library/react';
|
||||
import {vi,beforeEach,afterEach,it,expect} from 'vitest';
|
||||
import PodcastInlinePlayer from '../PodcastInlinePlayer';
|
||||
vi.mock('../SafeImage',()=>({default:({alt}:{alt:string})=><img alt={alt}/>}));
|
||||
vi.mock('../../lib/media',()=>({getMediaUrl:(s:string)=>s}));
|
||||
const podcast={audioUrl:'/test.mp3',title:'Clinical audio',description:'d'.repeat(140)};
|
||||
beforeEach(()=>{vi.spyOn(HTMLMediaElement.prototype,'play').mockResolvedValue();vi.spyOn(HTMLMediaElement.prototype,'pause').mockImplementation(()=>{});});
|
||||
afterEach(()=>{cleanup();vi.restoreAllMocks();});
|
||||
function setup(){const v=render(<PodcastInlinePlayer podcast={podcast}/>);const audio=v.container.querySelector('audio')!;Object.defineProperty(audio,'duration',{configurable:true,value:100});return {audio,...v};}
|
||||
it('plays, pauses and ends',()=>{const {audio}=setup();fireEvent.click(screen.getByTitle('پخش'));expect(audio.play).toHaveBeenCalled();Object.defineProperty(audio,'paused',{configurable:true,value:false});fireEvent.click(screen.getByTitle('توقف'));expect(audio.pause).toHaveBeenCalled();fireEvent.play(audio);fireEvent.ended(audio);expect(screen.getByTitle('پخش')).toBeInTheDocument();});
|
||||
it('does not claim playback when play rejects',async()=>{vi.mocked(HTMLMediaElement.prototype.play).mockRejectedValueOnce(new Error('blocked'));vi.spyOn(console,'error').mockImplementation(()=>{});setup();fireEvent.click(screen.getByTitle('پخش'));await waitFor(()=>expect(screen.getByTitle('پخش')).toBeInTheDocument());});
|
||||
it('seeks waveform and clamps skip boundaries',()=>{const {audio}=setup();fireEvent.loadedMetadata(audio);const wave=screen.getByTitle('برای رفتن به زمان مورد نظر کلیک کنید');vi.spyOn(wave,'getBoundingClientRect').mockReturnValue({left:10,width:200} as DOMRect);fireEvent.click(wave,{clientX:110});expect(audio.currentTime).toBe(50);audio.currentTime=98;fireEvent.click(screen.getByTitle('۱۵ ثانیه جلو'));expect(audio.currentTime).toBe(100);audio.currentTime=2;fireEvent.click(screen.getByTitle('۱۵ ثانیه عقب'));expect(audio.currentTime).toBe(0);});
|
||||
it('ignores seeking before metadata and shows elapsed time',()=>{const {audio}=setup();fireEvent.click(screen.getByTitle('برای رفتن به زمان مورد نظر کلیک کنید'),{clientX:100});expect(audio.currentTime).toBe(0);audio.currentTime=65;fireEvent.timeUpdate(audio);expect(screen.getByText('01:05')).toBeInTheDocument();});
|
||||
it('changes speed and dismisses rate menu outside',()=>{const {audio}=setup();fireEvent.click(screen.getByTitle('سرعت پخش'));fireEvent.click(screen.getByText('1.5x'));expect(audio.playbackRate).toBe(1.5);fireEvent.click(screen.getByTitle('سرعت پخش'));fireEvent.mouseDown(document.body);expect(screen.queryByText('2.5x')).not.toBeInTheDocument();});
|
||||
it('controls volume and mute',()=>{const {audio}=setup();fireEvent.change(screen.getByRole('slider'),{target:{value:'0'}});expect(audio.muted).toBe(true);fireEvent.change(screen.getByRole('slider'),{target:{value:'0.6'}});expect(audio.volume).toBe(0.6);expect(audio.muted).toBe(false);fireEvent.click(screen.getByTitle('بیصدا'));expect(audio.muted).toBe(true);});
|
||||
it('expands and collapses description',()=>{setup();fireEvent.click(screen.getByText('مشاهده متن کامل'));expect(screen.getByText(podcast.description)).toBeInTheDocument();fireEvent.click(screen.getByText('بستن متن'));expect(screen.queryByText(podcast.description)).not.toBeInTheDocument();});
|
||||
it('uses clipboard if native sharing absent',async()=>{Object.defineProperty(navigator,'share',{configurable:true,value:undefined});const writeText=vi.fn().mockResolvedValue(undefined);Object.defineProperty(navigator,'clipboard',{configurable:true,value:{writeText}});setup();fireEvent.click(screen.getByTitle('اشتراکگذاری'));await waitFor(()=>expect(writeText).toHaveBeenCalledWith(window.location.href));});
|
||||
@@ -0,0 +1,217 @@
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, act } from '@testing-library/react';
|
||||
import PodcastPlayerModal from '../PodcastPlayerModal';
|
||||
|
||||
// Mock motion/react
|
||||
vi.mock('motion/react', () => ({
|
||||
AnimatePresence: ({ children }: { children: React.ReactNode }) => <>{children}</>,
|
||||
motion: {
|
||||
div: ({ children, onClick, className, ...props }: any) => (
|
||||
<div onClick={onClick} className={className} {...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="podcast-cover" />
|
||||
),
|
||||
}));
|
||||
|
||||
describe('PodcastPlayerModal Component', () => {
|
||||
const mockPodcast = {
|
||||
audioUrl: 'https://canina.ir/audio/canhydrox-review.mp3',
|
||||
title: 'بررسی بالینی قرص کانهیدروکس',
|
||||
description: 'توضیحات تکمیلی پیرامون جذب کلسیم و مفاصل در توله سگها.',
|
||||
cover: 'https://canina.ir/images/canhydrox-cover.jpg',
|
||||
productName: 'کانهیدروکس گگ',
|
||||
};
|
||||
|
||||
const mockOnClose = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
window.HTMLMediaElement.prototype.play = vi.fn().mockImplementation(() => Promise.resolve());
|
||||
window.HTMLMediaElement.prototype.pause = vi.fn();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('does not render anything when isOpen is false', () => {
|
||||
const { container } = render(
|
||||
<PodcastPlayerModal isOpen={false} onClose={mockOnClose} podcast={mockPodcast} />
|
||||
);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('does not render anything when podcast is null', () => {
|
||||
const { container } = render(
|
||||
<PodcastPlayerModal isOpen={true} onClose={mockOnClose} podcast={null} />
|
||||
);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('renders podcast metadata, cover art, and triggers onClose when close button clicked', () => {
|
||||
render(
|
||||
<PodcastPlayerModal isOpen={true} onClose={mockOnClose} podcast={mockPodcast} />
|
||||
);
|
||||
|
||||
expect(screen.getByText('بررسی بالینی قرص کانهیدروکس')).toBeInTheDocument();
|
||||
expect(screen.getByText(/محصول: کانهیدروکس گگ/)).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText('توضیحات تکمیلی پیرامون جذب کلسیم و مفاصل در توله سگها.')
|
||||
).toBeInTheDocument();
|
||||
|
||||
const cover = screen.getByTestId('podcast-cover');
|
||||
expect(cover).toHaveAttribute('src', mockPodcast.cover);
|
||||
|
||||
const closeBtn = screen.getByTitle('بستن');
|
||||
fireEvent.click(closeBtn);
|
||||
expect(mockOnClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('toggles audio play and pause states when play/pause button is clicked', () => {
|
||||
const { container } = render(
|
||||
<PodcastPlayerModal isOpen={true} onClose={mockOnClose} podcast={mockPodcast} />
|
||||
);
|
||||
|
||||
const audioEl = container.querySelector('audio') as HTMLAudioElement;
|
||||
expect(audioEl).toBeTruthy();
|
||||
expect(audioEl.src).toBe(mockPodcast.audioUrl);
|
||||
|
||||
// In JSDOM, HTMLAudioElement.paused is true by default
|
||||
// Clicking the play button when paused calls audio.play()
|
||||
const toggleBtn = screen.getByTitle('توقف');
|
||||
expect(toggleBtn).toBeInTheDocument();
|
||||
|
||||
// Set paused to false to simulate playing
|
||||
Object.defineProperty(audioEl, 'paused', { value: false, writable: true });
|
||||
fireEvent.click(toggleBtn);
|
||||
expect(audioEl.pause).toHaveBeenCalled();
|
||||
expect(screen.getByTitle('پخش')).toBeInTheDocument();
|
||||
|
||||
// Now set paused to true and click play
|
||||
Object.defineProperty(audioEl, 'paused', { value: true, writable: true });
|
||||
fireEvent.click(screen.getByTitle('پخش'));
|
||||
expect(audioEl.play).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('skips forward and backward 15 seconds', () => {
|
||||
const { container } = render(
|
||||
<PodcastPlayerModal isOpen={true} onClose={mockOnClose} podcast={mockPodcast} />
|
||||
);
|
||||
|
||||
const audioEl = container.querySelector('audio') as HTMLAudioElement;
|
||||
Object.defineProperty(audioEl, 'duration', { value: 300, configurable: true });
|
||||
audioEl.currentTime = 50;
|
||||
|
||||
const skipForwardBtn = screen.getByTitle('۱۵ ثانیه جلو');
|
||||
const skipBackBtn = screen.getByTitle('۱۵ ثانیه عقب');
|
||||
|
||||
fireEvent.click(skipForwardBtn);
|
||||
expect(audioEl.currentTime).toBe(65);
|
||||
|
||||
fireEvent.click(skipBackBtn);
|
||||
expect(audioEl.currentTime).toBe(50);
|
||||
});
|
||||
|
||||
it('changes playback rate via speed dropdown menu', () => {
|
||||
const { container } = render(
|
||||
<PodcastPlayerModal isOpen={true} onClose={mockOnClose} podcast={mockPodcast} />
|
||||
);
|
||||
|
||||
const audioEl = container.querySelector('audio') as HTMLAudioElement;
|
||||
const speedBtn = screen.getByTitle('سرعت پخش');
|
||||
expect(speedBtn).toHaveTextContent('1x');
|
||||
|
||||
fireEvent.click(speedBtn);
|
||||
|
||||
const option15 = screen.getByRole('button', { name: '1.5x' });
|
||||
fireEvent.click(option15);
|
||||
|
||||
expect(audioEl.playbackRate).toBe(1.5);
|
||||
expect(speedBtn).toHaveTextContent('1.5x');
|
||||
});
|
||||
|
||||
it('handles volume slider adjustments and mute toggle', () => {
|
||||
const { container } = render(
|
||||
<PodcastPlayerModal isOpen={true} onClose={mockOnClose} podcast={mockPodcast} />
|
||||
);
|
||||
|
||||
const audioEl = container.querySelector('audio') as HTMLAudioElement;
|
||||
const volumeInput = container.querySelector('input[type="range"]') as HTMLInputElement;
|
||||
|
||||
// Change volume to 0.4
|
||||
fireEvent.change(volumeInput, { target: { value: '0.4' } });
|
||||
expect(audioEl.volume).toBe(0.4);
|
||||
|
||||
// Click mute button
|
||||
const muteBtn = screen.getByTitle('بیصدا');
|
||||
fireEvent.click(muteBtn);
|
||||
expect(audioEl.muted).toBe(true);
|
||||
|
||||
// Unmute
|
||||
const unmuteBtn = screen.getByTitle('صدا وصل');
|
||||
fireEvent.click(unmuteBtn);
|
||||
expect(audioEl.muted).toBe(false);
|
||||
});
|
||||
|
||||
it('shares or copies podcast URL to clipboard when share button is clicked', async () => {
|
||||
const writeTextMock = vi.fn().mockResolvedValue(undefined);
|
||||
Object.assign(navigator, {
|
||||
clipboard: {
|
||||
writeText: writeTextMock,
|
||||
},
|
||||
});
|
||||
|
||||
render(
|
||||
<PodcastPlayerModal isOpen={true} onClose={mockOnClose} podcast={mockPodcast} />
|
||||
);
|
||||
|
||||
const shareBtn = screen.getByTitle('اشتراکگذاری');
|
||||
await act(async () => {
|
||||
fireEvent.click(shareBtn);
|
||||
});
|
||||
|
||||
expect(writeTextMock).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('triggers file download when download button is clicked', () => {
|
||||
render(
|
||||
<PodcastPlayerModal isOpen={true} onClose={mockOnClose} podcast={mockPodcast} />
|
||||
);
|
||||
|
||||
const appendChildSpy = vi.spyOn(document.body, 'appendChild');
|
||||
const removeChildSpy = vi.spyOn(document.body, 'removeChild');
|
||||
|
||||
const downloadBtn = screen.getByTitle('دانلود فایل صوتی');
|
||||
fireEvent.click(downloadBtn);
|
||||
|
||||
expect(appendChildSpy).toHaveBeenCalled();
|
||||
expect(removeChildSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('handles audio metadata loading and time updates correctly', () => {
|
||||
const { container } = render(
|
||||
<PodcastPlayerModal isOpen={true} onClose={mockOnClose} podcast={mockPodcast} />
|
||||
);
|
||||
|
||||
const audioEl = container.querySelector('audio') as HTMLAudioElement;
|
||||
Object.defineProperty(audioEl, 'duration', { value: 125, configurable: true });
|
||||
Object.defineProperty(audioEl, 'currentTime', { value: 45, configurable: true });
|
||||
|
||||
act(() => {
|
||||
fireEvent.loadedMetadata(audioEl);
|
||||
fireEvent.timeUpdate(audioEl);
|
||||
});
|
||||
|
||||
expect(screen.getByText('00:45')).toBeInTheDocument();
|
||||
expect(screen.getByText('02:05')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,259 @@
|
||||
"use client";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import PrescriptionUploadModal from "../PrescriptionUploadModal";
|
||||
import { useUserStore } from "../../lib/store/userStore";
|
||||
import { usePetStore } from "../../lib/store/usePetStore";
|
||||
import api from "../../lib/services/api";
|
||||
import { toast } from "sonner";
|
||||
|
||||
vi.mock("../../lib/store/userStore", () => ({
|
||||
useUserStore: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/store/usePetStore", () => ({
|
||||
usePetStore: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/services/api", () => ({
|
||||
default: {
|
||||
post: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("sonner", () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockPets = [
|
||||
{
|
||||
id: "pet-1",
|
||||
name: "مکس",
|
||||
type: "سگ",
|
||||
breed: "ژرمن شپرد",
|
||||
age: 3,
|
||||
weight: 28,
|
||||
},
|
||||
{
|
||||
id: "pet-2",
|
||||
name: "لونا",
|
||||
type: "گربه",
|
||||
breed: "بریتیش",
|
||||
age: 2,
|
||||
weight: 4.5,
|
||||
},
|
||||
];
|
||||
|
||||
describe("PrescriptionUploadModal Component", () => {
|
||||
const mockOnClose = vi.fn();
|
||||
const mockAddPet = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
global.URL.createObjectURL = vi.fn(() => "blob:http://localhost/mock-file");
|
||||
|
||||
vi.mocked(useUserStore).mockReturnValue({
|
||||
isLoggedIn: true,
|
||||
profile: { mobile: "09123456789" },
|
||||
} as any);
|
||||
|
||||
vi.mocked(usePetStore).mockReturnValue({
|
||||
pets: mockPets,
|
||||
activePetId: "pet-1",
|
||||
addPet: mockAddPet,
|
||||
} as any);
|
||||
});
|
||||
|
||||
it("does not render modal when isOpen is false", () => {
|
||||
const { container } = render(
|
||||
<PrescriptionUploadModal isOpen={false} onClose={mockOnClose} />
|
||||
);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it("renders modal header, existing pets, and prefilled phone when isOpen is true", () => {
|
||||
render(<PrescriptionUploadModal isOpen={true} onClose={mockOnClose} />);
|
||||
|
||||
expect(screen.getByText("بررسی تخصصی نسخه دامپزشک")).toBeInTheDocument();
|
||||
expect(screen.getByText(/مکس/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/لونا/)).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue("09123456789")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows error when trying to submit without uploading a file", async () => {
|
||||
render(<PrescriptionUploadModal isOpen={true} onClose={mockOnClose} />);
|
||||
|
||||
const submitBtn = screen.getByRole("button", { name: /ارسال نسخه و ثبت درخواست تامین/ });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
expect(toast.error).toHaveBeenCalledWith("لطفاً تصویر یا فایل نسخه پزشکی را انتخاب کنید.");
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows error when phone number format is invalid", async () => {
|
||||
vi.mocked(useUserStore).mockReturnValue({
|
||||
isLoggedIn: false,
|
||||
profile: null,
|
||||
} as any);
|
||||
|
||||
render(<PrescriptionUploadModal isOpen={true} onClose={mockOnClose} />);
|
||||
|
||||
// Upload mock file
|
||||
const file = new File(["dummy content"], "prescription.jpg", { type: "image/jpeg" });
|
||||
const input = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { files: [file] } });
|
||||
|
||||
// Enter invalid phone
|
||||
const phoneInput = screen.getByPlaceholderText("۰۹۱۲۳۴۵۶۷۸۹");
|
||||
fireEvent.change(phoneInput, { target: { value: "02188884444" } });
|
||||
|
||||
const submitBtn = screen.getByRole("button", { name: /ارسال نسخه و ثبت درخواست تامین/ });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
expect(toast.error).toHaveBeenCalledWith(expect.stringContaining("شماره همراه معتبر نیست"));
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("allows selecting 'همدم جدید' and shows inline pet creation inputs", async () => {
|
||||
render(<PrescriptionUploadModal isOpen={true} onClose={mockOnClose} />);
|
||||
|
||||
const newPetBtn = screen.getByText("همدم جدید");
|
||||
fireEvent.click(newPetBtn);
|
||||
|
||||
expect(screen.getByPlaceholderText("نام حیوان خانگی *")).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText("نژاد (مثلاً ژرمن، پرشین)")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("validates missing pet name when 'همدم جدید' is selected", async () => {
|
||||
render(<PrescriptionUploadModal isOpen={true} onClose={mockOnClose} />);
|
||||
|
||||
// Upload mock file
|
||||
const file = new File(["dummy"], "rx.png", { type: "image/png" });
|
||||
const input = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { files: [file] } });
|
||||
|
||||
const newPetBtn = screen.getByText("همدم جدید");
|
||||
fireEvent.click(newPetBtn);
|
||||
|
||||
const submitBtn = screen.getByRole("button", { name: /ارسال نسخه و ثبت درخواست تامین/ });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
expect(toast.error).toHaveBeenCalledWith("لطفاً نام همدم (پت) را وارد کنید.");
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("successfully uploads prescription and creates pet when new pet info is provided", async () => {
|
||||
vi.mocked(api.post)
|
||||
.mockResolvedValueOnce({
|
||||
data: { success: true, url: "https://cdn.canina.ir/rx-123.jpg" },
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
data: { success: true, id: "presc-999" },
|
||||
});
|
||||
|
||||
render(<PrescriptionUploadModal isOpen={true} onClose={mockOnClose} />);
|
||||
|
||||
// 1. Upload file
|
||||
const file = new File(["rx binary"], "doctor_prescription.pdf", { type: "application/pdf" });
|
||||
const input = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { files: [file] } });
|
||||
|
||||
// 2. Select new pet and fill details
|
||||
fireEvent.click(screen.getByText("همدم جدید"));
|
||||
fireEvent.change(screen.getByPlaceholderText("نام حیوان خانگی *"), {
|
||||
target: { value: "تدی" },
|
||||
});
|
||||
fireEvent.change(screen.getByPlaceholderText("نژاد (مثلاً ژرمن، پرشین)"), {
|
||||
target: { value: "پامرانین" },
|
||||
});
|
||||
fireEvent.change(screen.getByPlaceholderText("سن (سال)"), {
|
||||
target: { value: "1.5" },
|
||||
});
|
||||
fireEvent.change(screen.getByPlaceholderText("وزن (کیلوگرم)"), {
|
||||
target: { value: "3.2" },
|
||||
});
|
||||
|
||||
// 3. Enter doctor notes
|
||||
const notesInput = screen.getByPlaceholderText("نکات پزشک، حساسیت دارویی یا شرایط خاص...");
|
||||
fireEvent.change(notesInput, { target: { value: "روزی یک قرص بعد از غذا" } });
|
||||
|
||||
// 4. Submit form
|
||||
const submitBtn = screen.getByRole("button", { name: /ارسال نسخه و ثبت درخواست تامین/ });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
// First api.post: file upload
|
||||
expect(api.post).toHaveBeenCalledWith(
|
||||
"/prescriptions/upload",
|
||||
expect.any(FormData),
|
||||
expect.objectContaining({
|
||||
headers: { "Content-Type": "multipart/form-data" },
|
||||
})
|
||||
);
|
||||
|
||||
// Second api.post: prescription creation
|
||||
expect(api.post).toHaveBeenCalledWith(
|
||||
"/prescriptions",
|
||||
expect.objectContaining({
|
||||
fileUrl: "https://cdn.canina.ir/rx-123.jpg",
|
||||
phone: "09123456789",
|
||||
petName: "تدی",
|
||||
petType: "سگ",
|
||||
petBreed: "پامرانین",
|
||||
petAge: 1.5,
|
||||
petWeight: 3.2,
|
||||
notes: "روزی یک قرص بعد از غذا",
|
||||
})
|
||||
);
|
||||
|
||||
// Add pet called
|
||||
expect(mockAddPet).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
name: "تدی",
|
||||
type: "سگ",
|
||||
breed: "پامرانین",
|
||||
age: 1.5,
|
||||
weight: 3.2,
|
||||
})
|
||||
);
|
||||
|
||||
// Success view displayed
|
||||
expect(screen.getByText("نسخه با موفقیت ثبت شد")).toBeInTheDocument();
|
||||
expect(toast.success).toHaveBeenCalledWith("نسخه پزشکی شما با موفقیت ثبت شد.");
|
||||
});
|
||||
|
||||
// Close success view
|
||||
fireEvent.click(screen.getByRole("button", { name: "متوجه شدم" }));
|
||||
expect(mockOnClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("handles upload or submission network errors gracefully", async () => {
|
||||
vi.mocked(api.post).mockRejectedValueOnce(new Error("Network Gateway Timeout"));
|
||||
|
||||
render(<PrescriptionUploadModal isOpen={true} onClose={mockOnClose} />);
|
||||
|
||||
const file = new File(["dummy"], "rx.png", { type: "image/png" });
|
||||
const input = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { files: [file] } });
|
||||
|
||||
const submitBtn = screen.getByRole("button", { name: /ارسال نسخه و ثبت درخواست تامین/ });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(toast.error).toHaveBeenCalledWith("خطا در ارسال نسخه پزشکی. لطفاً مجدداً تلاش کنید.");
|
||||
expect(screen.queryByText("نسخه با موفقیت ثبت شد")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("closes modal when clicking close icon button", () => {
|
||||
render(<PrescriptionUploadModal isOpen={true} onClose={mockOnClose} />);
|
||||
|
||||
const closeBtn = screen.getByLabelText("بستن پنجره");
|
||||
fireEvent.click(closeBtn);
|
||||
expect(mockOnClose).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,300 @@
|
||||
"use client";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import { ProductCard } from "../FeaturedProducts";
|
||||
import { ArchiveProductCard } from "../ArchivePage";
|
||||
import { Product } from "../../lib/data/products";
|
||||
import { useCartStore } from "../../lib/store/cartStore";
|
||||
import { usePetStore } from "../../lib/store/usePetStore";
|
||||
import { useCatalogMode } from "../../lib/useCatalogMode";
|
||||
import { toast } from "sonner";
|
||||
|
||||
const mockPush = vi.fn();
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({
|
||||
push: mockPush,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("sonner", () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/store/settingsStore", () => ({
|
||||
useSettingsStore: vi.fn((selector) => {
|
||||
if (typeof selector === "function") {
|
||||
return selector({ getText: (_key: string, def: string) => def });
|
||||
}
|
||||
return { getText: (_key: string, def: string) => def };
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/store/cartStore", () => ({
|
||||
useCartStore: Object.assign(
|
||||
vi.fn(() => ({
|
||||
addItem: vi.fn(),
|
||||
items: [],
|
||||
updateQuantity: vi.fn(),
|
||||
})),
|
||||
{
|
||||
getState: () => ({
|
||||
updateQuantity: vi.fn(),
|
||||
addItem: vi.fn(),
|
||||
items: [],
|
||||
}),
|
||||
}
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/store/usePetStore", () => ({
|
||||
usePetStore: vi.fn(() => ({
|
||||
getActivePet: () => null,
|
||||
pets: [],
|
||||
activePetId: null,
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/useCatalogMode", () => ({
|
||||
useCatalogMode: vi.fn(() => ({
|
||||
showPrices: true,
|
||||
allowCart: true,
|
||||
showPreorderBtn: false,
|
||||
})),
|
||||
}));
|
||||
|
||||
const sampleProduct: Product = {
|
||||
id: "prod-canina-1",
|
||||
name: "Canhydrox GAG",
|
||||
nameFa: "قرص کانهیدروکس گگ",
|
||||
nameEn: "Canina Canhydrox GAG",
|
||||
description: "مکمل تخصصی مفاصل و استخوان سگ",
|
||||
shortDescription: "تقویت کننده تاندون و استخوان بندی سگ",
|
||||
price: "۱,۲۵۰,۰۰۰ تومان",
|
||||
priceValue: 1250000,
|
||||
category: "joints",
|
||||
image: "/images/canhydrox.png",
|
||||
packageSize: "100",
|
||||
suitableFor: "سگ",
|
||||
symptoms: ["درد مفاصل", "لنگیدن"],
|
||||
benefits: "تقویت بافت همبند و غضروف",
|
||||
calculateDosage: vi.fn(),
|
||||
};
|
||||
|
||||
describe("ProductCard Component (FeaturedProducts)", () => {
|
||||
const mockAddItem = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(useCartStore).mockReturnValue({
|
||||
addItem: mockAddItem,
|
||||
items: [],
|
||||
updateQuantity: vi.fn(),
|
||||
} as any);
|
||||
|
||||
vi.mocked(usePetStore).mockReturnValue({
|
||||
getActivePet: () => null,
|
||||
pets: [],
|
||||
activePetId: null,
|
||||
} as any);
|
||||
|
||||
vi.mocked(useCatalogMode).mockReturnValue({
|
||||
showPrices: true,
|
||||
allowCart: true,
|
||||
showPreorderBtn: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("renders product Persian name, English name, and category badge", () => {
|
||||
render(<ProductCard product={sampleProduct} />);
|
||||
|
||||
expect(screen.getByText("قرص کانهیدروکس گگ")).toBeInTheDocument();
|
||||
expect(screen.getByText("Canina Canhydrox GAG")).toBeInTheDocument();
|
||||
expect(screen.getByText("joints")).toBeInTheDocument();
|
||||
expect(screen.getByText("۱,۲۵۰,۰۰۰ تومان")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("navigates to product detail page on card click", () => {
|
||||
render(<ProductCard product={sampleProduct} />);
|
||||
|
||||
fireEvent.click(screen.getByText("قرص کانهیدروکس گگ"));
|
||||
expect(mockPush).toHaveBeenCalledWith("/shop/prod-canina-1");
|
||||
});
|
||||
|
||||
it("adds product to cart when shopping cart button is clicked", () => {
|
||||
render(<ProductCard product={sampleProduct} />);
|
||||
|
||||
const cartBtn = screen.getByTitle("افزودن به سبد خرید");
|
||||
fireEvent.click(cartBtn);
|
||||
|
||||
expect(mockAddItem).toHaveBeenCalledWith(sampleProduct, 1);
|
||||
expect(toast.success).toHaveBeenCalledWith("قرص کانهیدروکس گگ به سبد خرید اضافه شد.");
|
||||
});
|
||||
|
||||
it("renders pet compatibility alert badge when pet is not compatible with product species", () => {
|
||||
vi.mocked(usePetStore).mockReturnValue({
|
||||
getActivePet: () => ({
|
||||
id: "pet-cat",
|
||||
name: "میشا",
|
||||
type: "گربه",
|
||||
breed: "پرشین",
|
||||
medicalConditions: [],
|
||||
}),
|
||||
pets: [],
|
||||
activePetId: "pet-cat",
|
||||
} as any);
|
||||
|
||||
render(<ProductCard product={sampleProduct} />);
|
||||
|
||||
expect(screen.getByText(/مخصوص سگ/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders pet compatibility success recommendation when pet symptom matches product", () => {
|
||||
vi.mocked(usePetStore).mockReturnValue({
|
||||
getActivePet: () => ({
|
||||
id: "pet-dog",
|
||||
name: "ببری",
|
||||
type: "سگ",
|
||||
breed: "ژرمن",
|
||||
medicalConditions: ["درد مفاصل"],
|
||||
}),
|
||||
pets: [],
|
||||
activePetId: "pet-dog",
|
||||
} as any);
|
||||
|
||||
render(<ProductCard product={sampleProduct} />);
|
||||
|
||||
expect(screen.getByText(/توصیه شده برای/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/ببری/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders preorder button badge when showPreorderBtn is enabled", () => {
|
||||
vi.mocked(useCatalogMode).mockReturnValue({
|
||||
showPrices: true,
|
||||
allowCart: false,
|
||||
showPreorderBtn: true,
|
||||
});
|
||||
|
||||
render(<ProductCard product={sampleProduct} />);
|
||||
|
||||
expect(screen.getByText("ثبت پیشخرید")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("hides price and displays fallback when showPrices is false", () => {
|
||||
vi.mocked(useCatalogMode).mockReturnValue({
|
||||
showPrices: false,
|
||||
allowCart: false,
|
||||
showPreorderBtn: false,
|
||||
});
|
||||
|
||||
render(<ProductCard product={sampleProduct} />);
|
||||
|
||||
expect(screen.getByText("تماس بگیرید")).toBeInTheDocument();
|
||||
expect(screen.queryByTitle('افزودن به سبد خرید')).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByText('تماس بگیرید'));
|
||||
expect(mockAddItem).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("ArchiveProductCard Component (ArchivePage)", () => {
|
||||
const mockAddItem = vi.fn();
|
||||
const mockUpdateQuantity = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
(useCartStore as any).getState = () => ({
|
||||
updateQuantity: mockUpdateQuantity,
|
||||
addItem: mockAddItem,
|
||||
items: [],
|
||||
});
|
||||
|
||||
vi.mocked(useCartStore).mockImplementation(((selector?: any) => {
|
||||
const state = {
|
||||
addItem: mockAddItem,
|
||||
items: [],
|
||||
updateQuantity: mockUpdateQuantity,
|
||||
};
|
||||
if (typeof selector === "function") {
|
||||
return selector(state);
|
||||
}
|
||||
return state;
|
||||
}) as any);
|
||||
|
||||
vi.mocked(usePetStore).mockImplementation(((selector?: any) => {
|
||||
const state = {
|
||||
getActivePet: () => null,
|
||||
pets: [],
|
||||
activePetId: null,
|
||||
};
|
||||
if (typeof selector === "function") {
|
||||
return selector(state);
|
||||
}
|
||||
return state;
|
||||
}) as any);
|
||||
|
||||
vi.mocked(useCatalogMode).mockReturnValue({
|
||||
showPrices: true,
|
||||
allowCart: true,
|
||||
showPreorderBtn: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("renders catalog card with symptoms and add to cart button", () => {
|
||||
render(<ArchiveProductCard product={sampleProduct} />);
|
||||
|
||||
expect(screen.getByText("قرص کانهیدروکس گگ")).toBeInTheDocument();
|
||||
expect(screen.getByText("درد مفاصل")).toBeInTheDocument();
|
||||
expect(screen.getByText("خرید")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("adds item to cart on clicking 'خرید' button", () => {
|
||||
render(<ArchiveProductCard product={sampleProduct} />);
|
||||
|
||||
const buyBtn = screen.getByRole("button", { name: /خرید/ });
|
||||
fireEvent.click(buyBtn);
|
||||
|
||||
expect(mockAddItem).toHaveBeenCalledWith(sampleProduct, 1);
|
||||
expect(toast.success).toHaveBeenCalledWith(expect.stringContaining("به سبد خرید اضافه شد"));
|
||||
});
|
||||
|
||||
it("renders out-of-stock badge when packageSize is 0", () => {
|
||||
const outOfStockProduct = { ...sampleProduct, packageSize: "0" };
|
||||
render(<ArchiveProductCard product={outOfStockProduct} />);
|
||||
|
||||
expect(screen.getByText("ناموجود")).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'خرید' })).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByText('ناموجود'));
|
||||
expect(mockAddItem).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows quantity counter and buttons when item is already in cart", () => {
|
||||
vi.mocked(useCartStore).mockImplementation(((selector?: any) => {
|
||||
const state = {
|
||||
addItem: mockAddItem,
|
||||
items: [{ product: sampleProduct, quantity: 2 }],
|
||||
updateQuantity: mockUpdateQuantity,
|
||||
};
|
||||
if (typeof selector === "function") {
|
||||
return selector(state);
|
||||
}
|
||||
return state;
|
||||
}) as any);
|
||||
|
||||
render(<ArchiveProductCard product={sampleProduct} />);
|
||||
|
||||
const plusBtn = screen.getByRole("button", { name: "+" });
|
||||
const minusBtn = screen.getByRole("button", { name: "-" });
|
||||
|
||||
expect(plusBtn).toBeInTheDocument();
|
||||
expect(minusBtn).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(plusBtn);
|
||||
expect(mockUpdateQuantity).toHaveBeenCalledWith("prod-canina-1", 3);
|
||||
|
||||
fireEvent.click(minusBtn);
|
||||
expect(mockUpdateQuantity).toHaveBeenCalledWith("prod-canina-1", 1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
"use client";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import ProductDetailModal from "../catalog/ProductDetailModal";
|
||||
import { Product } from "../../lib/data/products";
|
||||
|
||||
// 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 mockProduct: Product = {
|
||||
id: "canhydrox-gag-100",
|
||||
artNo: "12345",
|
||||
name: "Canina Canhydrox GAG",
|
||||
category: "مفاصل و استخوان",
|
||||
price: "۱,۲۰۰,۰۰۰ تومان",
|
||||
priceValue: 1200000,
|
||||
image: "/images/canhydrox.png",
|
||||
unit: "100 عدد قرص",
|
||||
packageSize: 100,
|
||||
suitableFor: "سگهای تمامی نژادها",
|
||||
scientificTagline: "فرمول پیشرفته تقویت غضروف و مفاصل",
|
||||
description: "<p>محصولی فوقالعاده برای بازسازی مفاصل و پیشگیری از آرتروز</p>",
|
||||
main_ingredients: ["هیدروکسی آپاتیت", "عصاره صدف سبز", "سیلیکا"],
|
||||
dosage_logic: "روزانه ۲ عدد قرص به ازای هر ۱۰ کیلوگرم وزن بدن",
|
||||
specialist: {
|
||||
name: "دکتر مریم حسینی",
|
||||
title: "متخصص ارتوپدی دامپزشکی",
|
||||
message: "بهترین انتخاب برای رفع ناهنجاریهای مفصلی و اسکلتی تولهها و سگهای مسن.",
|
||||
image: "/images/specialist.png",
|
||||
},
|
||||
symptoms: ["درد مفاصل", "لنگش"],
|
||||
benefits: "افزایش انعطافپذیری و مقاومت استخوان",
|
||||
calculateDosage: vi.fn(),
|
||||
};
|
||||
|
||||
describe("ProductDetailModal Component (Catalog)", () => {
|
||||
const mockOnClose = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("renders nothing when product is null", () => {
|
||||
const { container } = render(
|
||||
<ProductDetailModal product={null} onClose={mockOnClose} />
|
||||
);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it("renders product information correctly when product is provided", () => {
|
||||
render(
|
||||
<ProductDetailModal
|
||||
product={mockProduct}
|
||||
categoryColor="#0284C7"
|
||||
onClose={mockOnClose}
|
||||
/>
|
||||
);
|
||||
|
||||
// Title and Category
|
||||
expect(screen.getByText("Canina Canhydrox GAG")).toBeInTheDocument();
|
||||
expect(screen.getByText("مفاصل و استخوان")).toBeInTheDocument();
|
||||
expect(screen.getByText(/کد کالا: 12345/)).toBeInTheDocument();
|
||||
expect(screen.getByText("فرمول پیشرفته تقویت غضروف و مفاصل")).toBeInTheDocument();
|
||||
|
||||
// Unit & Suitable for
|
||||
expect(screen.getByText(/وزن\/حجم: 100 عدد قرص/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/مناسب: سگهای تمامی نژادها/)).toBeInTheDocument();
|
||||
expect(screen.getByText("گرید دارویی آلمان")).toBeInTheDocument();
|
||||
|
||||
// Description (HTML sanitized)
|
||||
expect(screen.getByText(/محصولی فوقالعاده برای بازسازی مفاصل/)).toBeInTheDocument();
|
||||
|
||||
// Ingredients
|
||||
expect(screen.getByText("هیدروکسی آپاتیت")).toBeInTheDocument();
|
||||
expect(screen.getByText("عصاره صدف سبز")).toBeInTheDocument();
|
||||
expect(screen.getByText("سیلیکا")).toBeInTheDocument();
|
||||
|
||||
// Clinical dosage
|
||||
expect(screen.getByText("دستور مصرف بالینی و دوز توصیه شده:")).toBeInTheDocument();
|
||||
expect(screen.getByText("روزانه ۲ عدد قرص به ازای هر ۱۰ کیلوگرم وزن بدن")).toBeInTheDocument();
|
||||
|
||||
// Specialist advice
|
||||
expect(screen.getByText("دکتر مریم حسینی")).toBeInTheDocument();
|
||||
expect(screen.getByText("(متخصص ارتوپدی دامپزشکی)")).toBeInTheDocument();
|
||||
expect(screen.getByText(/بهترین انتخاب برای رفع ناهنجاریهای مفصلی/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("calls onClose when close button in header or footer is clicked", () => {
|
||||
render(
|
||||
<ProductDetailModal
|
||||
product={mockProduct}
|
||||
categoryColor="#10B981"
|
||||
onClose={mockOnClose}
|
||||
/>
|
||||
);
|
||||
|
||||
// Click header close button (aria-label="بستن")
|
||||
const headerCloseBtn = screen.getByLabelText("بستن");
|
||||
fireEvent.click(headerCloseBtn);
|
||||
expect(mockOnClose).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Click footer close button ("بستن جزئیات")
|
||||
const footerCloseBtn = screen.getByText("بستن جزئیات");
|
||||
fireEvent.click(footerCloseBtn);
|
||||
expect(mockOnClose).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("renders plain text description if description does not contain HTML tags", () => {
|
||||
const plainProduct = {
|
||||
...mockProduct,
|
||||
description: "این یک توضیح متنی ساده بدون هیچ برچسب اچتیامال است.",
|
||||
main_ingredients: [],
|
||||
dosage_logic: undefined,
|
||||
specialist: undefined,
|
||||
};
|
||||
|
||||
render(
|
||||
<ProductDetailModal
|
||||
product={plainProduct}
|
||||
onClose={mockOnClose}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText("این یک توضیح متنی ساده بدون هیچ برچسب اچتیامال است.")).toBeInTheDocument();
|
||||
expect(screen.queryByText("ترکیبات فعال و مواد موثره دارویی:")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("دستور مصرف بالینی و دوز توصیه شده:")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
"use client";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import ProductImageZoomModal from "../ProductImageZoomModal";
|
||||
|
||||
describe("ProductImageZoomModal Component", () => {
|
||||
const mockImages = [
|
||||
"/images/prod-1.jpg",
|
||||
"/images/prod-2.jpg",
|
||||
"/images/prod-3.jpg",
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should render modal with images and controls when isOpen is true", () => {
|
||||
render(
|
||||
<ProductImageZoomModal
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
images={mockImages}
|
||||
activeImage={mockImages[0]}
|
||||
onSelectImage={vi.fn()}
|
||||
productName="پتویتال کلسیم"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText("پتویتال کلسیم")).toBeInTheDocument();
|
||||
expect(screen.getByAltText("پتویتال کلسیم")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should not render modal content when isOpen is false", () => {
|
||||
render(
|
||||
<ProductImageZoomModal
|
||||
isOpen={false}
|
||||
onClose={vi.fn()}
|
||||
images={mockImages}
|
||||
activeImage={mockImages[0]}
|
||||
onSelectImage={vi.fn()}
|
||||
productName="پتویتال کلسیم"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.queryByText("پتویتال کلسیم")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should navigate to next and previous images", () => {
|
||||
const handleSelectImage = vi.fn();
|
||||
render(
|
||||
<ProductImageZoomModal
|
||||
isOpen={true}
|
||||
onClose={vi.fn()}
|
||||
images={mockImages}
|
||||
activeImage={mockImages[0]}
|
||||
onSelectImage={handleSelectImage}
|
||||
productName="پتویتال کلسیم"
|
||||
/>
|
||||
);
|
||||
|
||||
const thumbnails = screen.getAllByRole("button");
|
||||
expect(thumbnails.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("should trigger onClose when close button is clicked", () => {
|
||||
const handleClose = vi.fn();
|
||||
render(
|
||||
<ProductImageZoomModal
|
||||
isOpen={true}
|
||||
onClose={handleClose}
|
||||
images={mockImages}
|
||||
activeImage={mockImages[0]}
|
||||
onSelectImage={vi.fn()}
|
||||
productName="پتویتال کلسیم"
|
||||
/>
|
||||
);
|
||||
|
||||
const closeBtn = screen.getByTitle("بستن (Esc)");
|
||||
fireEvent.click(closeBtn);
|
||||
expect(handleClose).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import React from 'react';
|
||||
import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react';
|
||||
const h = vi.hoisted(() => ({ push: vi.fn(), back: vi.fn(), replace: vi.fn() }));
|
||||
vi.mock('next/navigation', () => ({ useRouter: () => h, useSearchParams: () => new URLSearchParams(window.location.search) }));
|
||||
vi.mock('motion/react', async () => {
|
||||
const R = await import('react'); const cache: Record<string, React.ComponentType<any>> = {};
|
||||
return { AnimatePresence: ({children}: any) => children, motion: new Proxy({}, { get: (_, tag: string) => cache[tag] ||= R.forwardRef(({children, ...props}: any, ref) => {
|
||||
const clean = Object.fromEntries(Object.entries(props).filter(([k]) => !['initial','animate','exit','transition','whileHover','whileTap','whileInView','viewport','layout','layoutId','drag','dragConstraints','dragElastic','onDragEnd'].includes(k)));
|
||||
return R.createElement(tag, {...clean, ref}, children);
|
||||
}) }) };
|
||||
});
|
||||
vi.mock('next/image', () => ({ default: ({unoptimized, priority, fill, ...props}: any) => <img {...props} /> }));
|
||||
vi.mock('sonner', () => ({ toast: {success: vi.fn(), error: vi.fn(), info: vi.fn()} }));
|
||||
import { toast } from 'sonner';
|
||||
afterEach(cleanup);
|
||||
import ProductPage from '../ProductPage';
|
||||
import { productService } from '../../lib/services/productService';
|
||||
vi.mock('../../lib/services/productService',()=>({productService:{getProductBySlug:vi.fn(),getProducts:vi.fn()}}));
|
||||
vi.mock('../../lib/services/api',()=>({default:{get:vi.fn().mockResolvedValue({data:null})}}));
|
||||
const state=vi.hoisted(()=>({addItem:vi.fn(),catalog:{isCatalogOnly:false,allowCart:true,showPrices:true,showPreorderBtn:false}}));
|
||||
vi.mock('../../lib/store/cartStore',()=>({useCartStore:()=>({addItem:state.addItem})}));
|
||||
vi.mock('../../lib/store/usePetStore',()=>({usePetStore:()=>({pets:[],getActivePet:()=>null})}));
|
||||
vi.mock('../../lib/store/settingsStore',()=>({useSettingsStore:(selector:any)=>selector({getText:(_:string,d:string)=>d,scientificTerms:{}})}));
|
||||
vi.mock('../../lib/useCatalogMode',()=>({useCatalogMode:()=>state.catalog}));
|
||||
const product={id:'p1',slug:'joint',artNo:'001',name:'Joint Support',scientificTagline:'Daily care',description:'Clinical description',price:'100 تومان',priceValue:100,category:'joints',unit:'tablets',packageSize:100,main_ingredients:[],dosage_logic:'Daily',benefits:'Mobility',symptoms:[],suitableFor:'سگ',analysis:{},feedingAdvice:'With food',image:'/p.png'};
|
||||
beforeEach(()=>{vi.clearAllMocks();Element.prototype.scrollIntoView=vi.fn();state.catalog={isCatalogOnly:false,allowCart:true,showPrices:true,showPreorderBtn:false};vi.mocked(productService.getProductBySlug).mockResolvedValue(product as any);vi.mocked(productService.getProducts).mockResolvedValue({data:[]} as any);});
|
||||
describe('ProductPage',()=>{
|
||||
it('shows loading state until product and related catalog settle',async()=>{let resolve!:(v:any)=>void;vi.mocked(productService.getProductBySlug).mockReturnValueOnce(new Promise(r=>{resolve=r;}));const {container}=render(<ProductPage productSlug="joint"/>);expect(container.querySelector('.animate-pulse')).toBeInTheDocument();resolve(product);await screen.findByTestId('product-desktop-add-to-cart-btn');expect(container.querySelector('.animate-pulse')).not.toBeInTheDocument();expect(productService.getProductBySlug).toHaveBeenCalledWith('joint');});
|
||||
it.each([null,undefined])('handles absent product %s',async value=>{vi.mocked(productService.getProductBySlug).mockResolvedValueOnce(value as any);render(<ProductPage productSlug="missing"/>);expect(await screen.findByText('محصول یافت نشد')).toBeInTheDocument();expect(state.addItem).not.toHaveBeenCalled();});
|
||||
it('handles rejected product request',async()=>{const err=vi.spyOn(console,'error').mockImplementation(()=>{});vi.mocked(productService.getProductBySlug).mockRejectedValueOnce(new Error('offline'));render(<ProductPage productSlug="joint"/>);await screen.findByText('محصول یافت نشد');expect(err).toHaveBeenCalled();err.mockRestore();});
|
||||
it('adds selected quantity with calculated dosage and respects quantity floor',async()=>{render(<ProductPage productSlug="joint"/>);const add=await screen.findByTestId('product-desktop-add-to-cart-btn');const minus=document.querySelector('svg.lucide-minus')!.closest('button')!;const plus=document.querySelector('svg.lucide-plus')!.closest('button')!;fireEvent.click(minus);fireEvent.click(add);expect(state.addItem).toHaveBeenLastCalledWith(product,1,{quantity:2,unit:'قرص'});fireEvent.click(plus);fireEvent.click(add);expect(state.addItem).toHaveBeenLastCalledWith(product,2,{quantity:2,unit:'قرص'});});
|
||||
it('uses dosage config and clamps dosage to maximum after weight change',async()=>{const api=(await import('../../lib/services/api')).default;vi.mocked(api.get).mockImplementation(async (url) => ({data:String(url).endsWith('/dosage-config') ? {baseWeightKg:10,baseDose:2,youngMultiplier:2,maxDailyDose:5,unit:'قرص'} : null}) as any);render(<ProductPage productSlug="joint"/>);await screen.findByTestId('product-desktop-add-to-cart-btn');await waitFor(()=>expect(api.get).toHaveBeenCalledWith('/products/p1/dosage-config'));fireEvent.change(screen.getByRole('slider'),{target:{value:'100'}});await waitFor(()=>{fireEvent.click(screen.getByTestId('product-desktop-add-to-cart-btn'));expect(state.addItem).toHaveBeenLastCalledWith(product,2,{quantity:5,unit:'قرص'});});});
|
||||
it('offers stock notification instead of cart for zero package size',async()=>{vi.mocked(productService.getProductBySlug).mockResolvedValueOnce({...product,packageSize:0} as any);render(<ProductPage productSlug="joint"/>);fireEvent.click(await screen.findByTestId('product-desktop-out-of-stock-btn'));expect(toast.info).toHaveBeenCalledWith('درخواست اطلاعرسانی موجودی ثبت شد');expect(state.addItem).not.toHaveBeenCalled();expect(screen.queryByTestId('product-desktop-add-to-cart-btn')).not.toBeInTheDocument();});
|
||||
it('catalog restriction hides cart and price and provides contact link',async()=>{state.catalog={isCatalogOnly:true,allowCart:false,showPrices:false,showPreorderBtn:false};render(<ProductPage productSlug="joint"/>);await screen.findByRole('link',{name:/مشاوره تخصصی با کارشناسان/});expect(screen.queryByTestId('product-desktop-add-to-cart-btn')).not.toBeInTheDocument();expect(screen.queryByText('100 تومان')).not.toBeInTheDocument();expect(state.addItem).not.toHaveBeenCalled();});
|
||||
});
|
||||
@@ -0,0 +1,144 @@
|
||||
"use client";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import ProductReviews from "../ProductReviews";
|
||||
import api from "../../lib/services/api";
|
||||
import { toast } from "sonner";
|
||||
|
||||
vi.mock("../../lib/services/api", () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("sonner", () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("ProductReviews Component", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should fetch and render approved reviews and rating stats", async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({
|
||||
data: {
|
||||
success: true,
|
||||
data: [
|
||||
{
|
||||
id: "rev-1",
|
||||
userName: "رضا کریمی",
|
||||
rating: 5,
|
||||
comment: "تاثیر فوقالعادهای روی اشتهای سگم داشت",
|
||||
adminReply: "خوشحالیم از رضایت شما!",
|
||||
createdAt: "2026-10-10T10:00:00Z",
|
||||
},
|
||||
],
|
||||
pagination: { totalPages: 1 },
|
||||
stats: { averageRating: 4.8, totalReviews: 12 },
|
||||
},
|
||||
});
|
||||
|
||||
render(
|
||||
<ProductReviews
|
||||
productId="prod-123"
|
||||
productName="کانویتال تونیک"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText("نظرات و تجربیات خریداران")).toBeInTheDocument();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("رضا کریمی")).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText("تاثیر فوقالعادهای روی اشتهای سگم داشت")
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText("خوشحالیم از رضایت شما!")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("should show empty review placeholder if no reviews exist", async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({
|
||||
data: {
|
||||
success: true,
|
||||
data: [],
|
||||
pagination: { totalPages: 1 },
|
||||
stats: { averageRating: 5, totalReviews: 0 },
|
||||
},
|
||||
});
|
||||
|
||||
render(
|
||||
<ProductReviews
|
||||
productId="prod-123"
|
||||
productName="کانویتال تونیک"
|
||||
/>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByText(/هنوز دیدگاهی برای این محصول ثبت نشده است/)
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("should validate and submit a new review", async () => {
|
||||
vi.mocked(api.get).mockResolvedValueOnce({
|
||||
data: {
|
||||
success: true,
|
||||
data: [],
|
||||
pagination: { totalPages: 1 },
|
||||
stats: { averageRating: 5, totalReviews: 0 },
|
||||
},
|
||||
});
|
||||
|
||||
vi.mocked(api.post).mockResolvedValueOnce({
|
||||
data: {
|
||||
success: true,
|
||||
message: "دیدگاه شما با موفقیت ثبت شد",
|
||||
},
|
||||
});
|
||||
|
||||
render(
|
||||
<ProductReviews
|
||||
productId="prod-123"
|
||||
productName="کانویتال تونیک"
|
||||
/>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByText(/هنوز دیدگاهی برای این محصول ثبت نشده است/)
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Open form button: "ثبت دیدگاه جدید"
|
||||
const openFormBtn = screen.getByText("ثبت دیدگاه جدید");
|
||||
fireEvent.click(openFormBtn);
|
||||
|
||||
const commentInput = screen.getByPlaceholderText(
|
||||
"تجربه خود را از نحوه مصرف، تغییرات بالینی پت و اثربخشی این مکمل بنویسید..."
|
||||
);
|
||||
fireEvent.change(commentInput, {
|
||||
target: { value: "کیفیت بسیار عالی و بستهبندی ارجینال آلمانی" },
|
||||
});
|
||||
|
||||
const submitBtn = screen.getByText("ثبت و ارسال دیدگاه");
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith(
|
||||
"/products/prod-123/reviews",
|
||||
expect.objectContaining({
|
||||
comment: "کیفیت بسیار عالی و بستهبندی ارجینال آلمانی",
|
||||
rating: 5,
|
||||
})
|
||||
);
|
||||
expect(toast.success).toHaveBeenCalledWith("دیدگاه شما با موفقیت ثبت شد");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,161 @@
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, act } from '@testing-library/react';
|
||||
import SafeImage from '../SafeImage';
|
||||
import { useSettingsStore } from '../../lib/store/settingsStore';
|
||||
|
||||
vi.mock('../../lib/store/settingsStore', () => ({
|
||||
useSettingsStore: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('SafeImage Component', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(useSettingsStore).mockImplementation((selector: any) => {
|
||||
const state = {
|
||||
getText: vi.fn((key: string, fallback: string) => {
|
||||
if (key === 'site_logo') return '/images/test-logo.png';
|
||||
return fallback;
|
||||
}),
|
||||
};
|
||||
return selector(state);
|
||||
});
|
||||
});
|
||||
|
||||
const triggerNextImageLoad = async (img: HTMLImageElement) => {
|
||||
img.decode = () => Promise.resolve();
|
||||
const propKey = Object.keys(img).find(k => k.startsWith('__reactProps'))!;
|
||||
await act(async () => {
|
||||
(img as any)[propKey].onLoad({ currentTarget: img });
|
||||
await new Promise(r => setTimeout(r, 10));
|
||||
});
|
||||
};
|
||||
|
||||
const triggerNextImageError = async (img: HTMLImageElement) => {
|
||||
const propKey = Object.keys(img).find(k => k.startsWith('__reactProps'))!;
|
||||
await act(async () => {
|
||||
(img as any)[propKey].onError({ currentTarget: img });
|
||||
});
|
||||
};
|
||||
|
||||
it('renders fallback UI when src is undefined or empty', () => {
|
||||
render(<SafeImage src="" alt="تست تصویر" fallbackText="تصویر موجود نیست" />);
|
||||
|
||||
expect(screen.getByText('تصویر موجود نیست')).toBeInTheDocument();
|
||||
expect(screen.getByText('Canina Pharma')).toBeInTheDocument();
|
||||
// Brand logo should be rendered when logoUrl exists in settings
|
||||
const logoImg = screen.getByAltText('تست تصویر');
|
||||
expect(logoImg).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders fallback UI with CANINA text badge when site_logo is empty', () => {
|
||||
vi.mocked(useSettingsStore).mockImplementation((selector: any) => {
|
||||
const state = {
|
||||
getText: vi.fn((_key: string, fallback: string) => fallback),
|
||||
};
|
||||
return selector(state);
|
||||
});
|
||||
|
||||
render(<SafeImage src="" fallbackText="در حال آمادهسازی..." />);
|
||||
|
||||
expect(screen.getByText('CANINA')).toBeInTheDocument();
|
||||
expect(screen.getByText('Canina Pharma')).toBeInTheDocument();
|
||||
expect(screen.getByText('در حال آمادهسازی...')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders the image element with correct attributes when valid src is provided', () => {
|
||||
render(
|
||||
<SafeImage
|
||||
src="https://canina.ir/product.jpg"
|
||||
alt="محصول شماره یک"
|
||||
className="custom-container"
|
||||
imgClassName="custom-img"
|
||||
width={300}
|
||||
height={300}
|
||||
/>
|
||||
);
|
||||
|
||||
const img = screen.getByAltText('محصول شماره یک');
|
||||
expect(img).toBeInTheDocument();
|
||||
expect(img).toHaveAttribute('src');
|
||||
expect(img.getAttribute('src')).toContain('product.jpg');
|
||||
expect(img).toHaveClass('custom-img');
|
||||
});
|
||||
|
||||
it('renders loading shimmer/sparkles state initially when priority is false, and hides it onLoad', async () => {
|
||||
const { container } = render(
|
||||
<SafeImage
|
||||
src="https://canina.ir/sample.jpg"
|
||||
alt="نمونه عکس"
|
||||
priority={false}
|
||||
/>
|
||||
);
|
||||
|
||||
// Shimmer pulse placeholder is rendered initially
|
||||
const pulseOverlay = container.querySelector('.animate-pulse');
|
||||
expect(pulseOverlay).toBeInTheDocument();
|
||||
|
||||
const img = screen.getByAltText('نمونه عکس') as HTMLImageElement;
|
||||
// Initially image has opacity-0
|
||||
expect(img).toHaveClass('opacity-0');
|
||||
|
||||
// Trigger image loaded
|
||||
await triggerNextImageLoad(img);
|
||||
|
||||
// Pulse overlay removed and image becomes visible
|
||||
expect(container.querySelector('.animate-pulse')).not.toBeInTheDocument();
|
||||
expect(img).toHaveClass('opacity-100');
|
||||
});
|
||||
|
||||
it('does not render loading overlay when priority is true', () => {
|
||||
const { container } = render(
|
||||
<SafeImage
|
||||
src="https://canina.ir/sample.jpg"
|
||||
alt="عکس مهم"
|
||||
priority={true}
|
||||
/>
|
||||
);
|
||||
|
||||
// Should not have loading overlay
|
||||
expect(container.querySelector('.animate-pulse')).not.toBeInTheDocument();
|
||||
const img = screen.getByAltText('عکس مهم');
|
||||
expect(img).toHaveClass('opacity-100');
|
||||
});
|
||||
|
||||
it('transitions to fallback UI when image onError fires', async () => {
|
||||
render(
|
||||
<SafeImage
|
||||
src="https://canina.ir/broken.jpg"
|
||||
alt="تصویر خراب"
|
||||
fallbackText="خطا در لود عکس"
|
||||
/>
|
||||
);
|
||||
|
||||
const img = screen.getByAltText('تصویر خراب') as HTMLImageElement;
|
||||
await triggerNextImageError(img);
|
||||
|
||||
// Fallback UI is now rendered
|
||||
expect(screen.getByText('خطا در لود عکس')).toBeInTheDocument();
|
||||
expect(screen.getByText('Canina Pharma')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('handles SVG, blob and unoptimized external domain sources properly', () => {
|
||||
const { rerender } = render(
|
||||
<SafeImage
|
||||
src="data:image/svg+xml;base64,PHN2Zz48L3N2Zz4="
|
||||
alt="دیتای تصویر"
|
||||
/>
|
||||
);
|
||||
let img = screen.getByAltText('دیتای تصویر');
|
||||
expect(img).toBeInTheDocument();
|
||||
|
||||
rerender(
|
||||
<SafeImage
|
||||
src="https://some-unlisted-domain.com/image.png"
|
||||
alt="دامین ناشناس"
|
||||
/>
|
||||
);
|
||||
img = screen.getByAltText('دامین ناشناس');
|
||||
expect(img).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import React from 'react';
|
||||
import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react';
|
||||
const h = vi.hoisted(() => ({ push: vi.fn(), back: vi.fn(), replace: vi.fn() }));
|
||||
vi.mock('next/navigation', () => ({ useRouter: () => h, useSearchParams: () => new URLSearchParams(window.location.search) }));
|
||||
vi.mock('motion/react', async () => {
|
||||
const R = await import('react'); const cache: Record<string, React.ComponentType<any>> = {};
|
||||
return { AnimatePresence: ({children}: any) => children, motion: new Proxy({}, { get: (_, tag: string) => cache[tag] ||= R.forwardRef(({children, ...props}: any, ref) => {
|
||||
const clean = Object.fromEntries(Object.entries(props).filter(([k]) => !['initial','animate','exit','transition','whileHover','whileTap','whileInView','viewport','layout','layoutId','drag','dragConstraints','dragElastic','onDragEnd'].includes(k)));
|
||||
return R.createElement(tag, {...clean, ref}, children);
|
||||
}) }) };
|
||||
});
|
||||
vi.mock('next/image', () => ({ default: ({unoptimized, priority, fill, ...props}: any) => <img {...props} /> }));
|
||||
vi.mock('sonner', () => ({ toast: {success: vi.fn(), error: vi.fn(), info: vi.fn()} }));
|
||||
import { toast } from 'sonner';
|
||||
afterEach(cleanup);
|
||||
import SearchResultsPage from '../SearchResultsPage';
|
||||
import { productService } from '../../lib/services/productService';
|
||||
vi.mock('../../lib/services/productService',()=>({productService:{getProducts:vi.fn()}}));
|
||||
const pet=vi.hoisted(()=>({active:null as any}));
|
||||
vi.mock('../../lib/store/usePetStore',()=>({usePetStore:()=>({getActivePet:()=>pet.active})}));
|
||||
const products=[
|
||||
{id:'a',slug:'alpha',name:'Joint Alpha',description:'Mobility support',main_ingredients:['Glucosamine'],symptoms:['pain'],suitableFor:'سگ',image:'/a.png',price:'100',category:'joints',benefits:'movement'},
|
||||
{id:'b',name:'Coat Beta',description:'Shiny fur',main_ingredients:['Biotin'],symptoms:['itch'],suitableFor:'گربه',image:'/b.png',price:'200',category:'skin',benefits:'coat'},
|
||||
{id:'c',name:'Both Gamma',description:'Daily care',main_ingredients:[],symptoms:[],suitableFor:'هر دو',image:'/c.png',price:'300',category:'care',benefits:'health'},
|
||||
{id:'d',name:'Fourth',description:'Daily',main_ingredients:[],symptoms:[],suitableFor:'سگ',image:'/d.png',price:'400',category:'care',benefits:'health'}];
|
||||
beforeEach(()=>{vi.clearAllMocks();pet.active=null;vi.mocked(productService.getProducts).mockResolvedValue({data:products} as any);});
|
||||
describe('SearchResultsPage',()=>{
|
||||
it.each(['JOINT','mobility','glucosamine','pain'])('searches field %s',async query=>{render(<SearchResultsPage query={query}/>);expect(await screen.findByRole('link',{name:/Joint Alpha/})).toHaveAttribute('href','/shop/alpha');expect(screen.getAllByRole('link')).toHaveLength(1);expect(productService.getProducts).toHaveBeenCalledWith({limit:999});});
|
||||
it('recomputes query without fetching and limits fallback suggestions',async()=>{const view=render(<SearchResultsPage query="Joint"/>);await screen.findByText('Joint Alpha');view.rerender(<SearchResultsPage query="missing"/>);expect(screen.getByText('نتیجهای یافت نشد')).toBeInTheDocument();expect(screen.getAllByRole('link')).toHaveLength(3);expect(screen.queryByText('Fourth')).not.toBeInTheDocument();expect(productService.getProducts).toHaveBeenCalledTimes(1);fireEvent.click(screen.getByRole('button',{name:'بازگشت'}));expect(h.back).toHaveBeenCalled();});
|
||||
it('handles service failure',async()=>{const err=vi.spyOn(console,'error').mockImplementation(()=>{});vi.mocked(productService.getProducts).mockRejectedValueOnce(new Error('offline'));render(<SearchResultsPage query="Joint"/>);await waitFor(()=>expect(err).toHaveBeenCalled());expect(screen.queryAllByRole('link')).toHaveLength(0);err.mockRestore();});
|
||||
it('shows recommendation, species mismatch and neutral compatibility',async()=>{pet.active={type:'سگ',name:'Rex',medicalConditions:['pain']};render(<SearchResultsPage query=""/>);await screen.findByText('Joint Alpha');expect(screen.getByText('توصیه شده برای Rex')).toBeInTheDocument();expect(screen.getByText('مخصوص گربه')).toBeInTheDocument();expect(screen.getAllByText('مناسب برای Rex')).toHaveLength(2);});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import SearchableSelect from '../SearchableSelect';
|
||||
|
||||
describe('SearchableSelect Component', () => {
|
||||
const options = ['تهران', 'اصفهان', 'شیراز', 'مشهد', 'تبریز'];
|
||||
|
||||
it('renders placeholder and toggles dropdown on click', () => {
|
||||
render(
|
||||
<SearchableSelect
|
||||
options={options}
|
||||
value=""
|
||||
onChange={vi.fn()}
|
||||
placeholder="انتخاب استان"
|
||||
/>,
|
||||
);
|
||||
|
||||
const button = screen.getByText('انتخاب استان');
|
||||
expect(button).toBeInTheDocument();
|
||||
|
||||
// Click to open
|
||||
fireEvent.click(button);
|
||||
expect(screen.getByPlaceholderText('جستجو...')).toBeInTheDocument();
|
||||
expect(screen.getByText('تهران')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('filters options based on search query', () => {
|
||||
render(
|
||||
<SearchableSelect
|
||||
options={options}
|
||||
value=""
|
||||
onChange={vi.fn()}
|
||||
placeholder="انتخاب استان"
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByText('انتخاب استان'));
|
||||
const searchInput = screen.getByPlaceholderText('جستجو...');
|
||||
|
||||
fireEvent.change(searchInput, { target: { value: 'شیراز' } });
|
||||
expect(screen.getByText('شیراز')).toBeInTheDocument();
|
||||
expect(screen.queryByText('تهران')).toBeNull();
|
||||
});
|
||||
|
||||
it('selects option, calls onChange and closes dropdown', () => {
|
||||
const handleChange = vi.fn();
|
||||
render(
|
||||
<SearchableSelect
|
||||
options={options}
|
||||
value=""
|
||||
onChange={handleChange}
|
||||
placeholder="انتخاب استان"
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByText('انتخاب استان'));
|
||||
fireEvent.click(screen.getByText('اصفهان'));
|
||||
|
||||
expect(handleChange).toHaveBeenCalledWith('اصفهان');
|
||||
// Dropdown should be closed, search input gone
|
||||
expect(screen.queryByPlaceholderText('جستجو...')).toBeNull();
|
||||
});
|
||||
|
||||
it('displays empty state message when search has no matches', () => {
|
||||
render(
|
||||
<SearchableSelect
|
||||
options={options}
|
||||
value=""
|
||||
onChange={vi.fn()}
|
||||
placeholder="انتخاب استان"
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByText('انتخاب استان'));
|
||||
const searchInput = screen.getByPlaceholderText('جستجو...');
|
||||
|
||||
fireEvent.change(searchInput, { target: { value: 'بوشهر' } });
|
||||
expect(screen.getByText('موردی یافت نشد')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
import React from 'react';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render } from '@testing-library/react';
|
||||
import {
|
||||
Skeleton,
|
||||
ProductCardSkeleton,
|
||||
ProductListSkeleton,
|
||||
PetProfileSkeleton,
|
||||
OrderRowSkeleton,
|
||||
} from '../Skeleton';
|
||||
|
||||
describe('Skeleton Components', () => {
|
||||
describe('Skeleton base component', () => {
|
||||
it('renders with default base classes including animation and shimmer', () => {
|
||||
const { container } = render(<Skeleton />);
|
||||
const el = container.firstElementChild;
|
||||
|
||||
expect(el).toBeInTheDocument();
|
||||
expect(el).toHaveClass('bg-medical-gray-100');
|
||||
expect(el).toHaveClass('animate-pulse');
|
||||
expect(el).toHaveClass('rounded-2xl');
|
||||
expect(el).toHaveClass('relative');
|
||||
expect(el).toHaveClass('overflow-hidden');
|
||||
// Shimmer pseudo element classes check
|
||||
expect(el?.className).toContain('before:absolute');
|
||||
expect(el?.className).toContain('before:inset-0');
|
||||
expect(el?.className).toContain('before:-translate-x-full');
|
||||
expect(el?.className).toContain('before:animate-[shimmer_2s_infinite]');
|
||||
expect(el?.className).toContain('before:bg-gradient-to-r');
|
||||
});
|
||||
|
||||
it('applies custom className sizing and styling correctly', () => {
|
||||
const { container } = render(<Skeleton className="w-32 h-8 rounded-full custom-skeleton-class" />);
|
||||
const el = container.firstElementChild;
|
||||
|
||||
expect(el).toHaveClass('w-32');
|
||||
expect(el).toHaveClass('h-8');
|
||||
expect(el).toHaveClass('rounded-full');
|
||||
expect(el).toHaveClass('custom-skeleton-class');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ProductCardSkeleton variant', () => {
|
||||
it('renders card skeleton layout with image, tags, titles, symptoms, and footer placeholders', () => {
|
||||
const { container } = render(<ProductCardSkeleton />);
|
||||
|
||||
const rootCard = container.firstElementChild;
|
||||
expect(rootCard).toHaveClass('bg-white');
|
||||
expect(rootCard).toHaveClass('rounded-[2.5rem]');
|
||||
expect(rootCard).toHaveClass('shadow-sm');
|
||||
|
||||
// Check skeleton elements inside
|
||||
const skeletons = container.querySelectorAll('.animate-pulse');
|
||||
expect(skeletons.length).toBeGreaterThanOrEqual(7);
|
||||
|
||||
// Verify aspect-square placeholder for product image
|
||||
const imagePlaceholder = container.querySelector('.aspect-square');
|
||||
expect(imagePlaceholder).toBeInTheDocument();
|
||||
expect(imagePlaceholder).toHaveClass('rounded-[2rem]', 'w-full', 'mb-6');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ProductListSkeleton variant', () => {
|
||||
it('renders horizontal list skeleton item with image thumb and info rows', () => {
|
||||
const { container } = render(<ProductListSkeleton />);
|
||||
|
||||
const root = container.firstElementChild;
|
||||
expect(root).toHaveClass('bg-white', 'rounded-2xl', 'p-3');
|
||||
|
||||
const skeletons = container.querySelectorAll('.animate-pulse');
|
||||
expect(skeletons.length).toBe(6); // thumb + 3 info rows + 2 footer action rows
|
||||
|
||||
// Thumbnail check
|
||||
const thumb = container.querySelector('.w-24.h-24');
|
||||
expect(thumb).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('PetProfileSkeleton variant', () => {
|
||||
it('renders pet profile skeleton layout with avatar, headers, badges, and stat cards', () => {
|
||||
const { container } = render(<PetProfileSkeleton />);
|
||||
|
||||
const root = container.firstElementChild;
|
||||
expect(root).toHaveClass('bg-white', 'rounded-[3rem]', 'shadow-2xl');
|
||||
|
||||
// Avatar placeholder
|
||||
const avatar = container.querySelector('.w-40.h-40');
|
||||
expect(avatar).toBeInTheDocument();
|
||||
|
||||
// Check 4 stat cards exist
|
||||
const statCards = container.querySelectorAll('.bg-medical-gray-50');
|
||||
expect(statCards.length).toBe(4);
|
||||
|
||||
const skeletons = container.querySelectorAll('.animate-pulse');
|
||||
expect(skeletons.length).toBeGreaterThanOrEqual(13); // avatar + 2 headers + 2 tags + 4*2 stats
|
||||
});
|
||||
});
|
||||
|
||||
describe('OrderRowSkeleton variant', () => {
|
||||
it('renders order row skeleton with thumbnail and order detail blocks', () => {
|
||||
const { container } = render(<OrderRowSkeleton />);
|
||||
|
||||
const root = container.firstElementChild;
|
||||
expect(root).toHaveClass('flex', 'items-center', 'gap-6', 'p-6');
|
||||
|
||||
const thumb = container.querySelector('.w-16.h-16');
|
||||
expect(thumb).toBeInTheDocument();
|
||||
|
||||
const skeletons = container.querySelectorAll('.animate-pulse');
|
||||
expect(skeletons.length).toBe(5); // thumb + 4 detail placeholders
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,294 @@
|
||||
"use client";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import React from "react";
|
||||
|
||||
// Mock motion/react to immediately render children without transition delays
|
||||
vi.mock("motion/react", () => ({
|
||||
AnimatePresence: ({ children }: { children: React.ReactNode }) => <>{children}</>,
|
||||
motion: {
|
||||
div: ({ children, ...props }: any) => <div {...props}>{children}</div>,
|
||||
button: ({ children, ...props }: any) => <button {...props}>{children}</button>,
|
||||
span: ({ children, ...props }: any) => <span {...props}>{children}</span>,
|
||||
},
|
||||
}));
|
||||
|
||||
import SmartAdvisor from "../SmartAdvisor";
|
||||
import { useUserStore } from "../../lib/store/userStore";
|
||||
import { useUIStore } from "../../lib/store/uiStore";
|
||||
import { usePetStore } from "../../lib/store/usePetStore";
|
||||
import api from "../../lib/services/api";
|
||||
|
||||
const mockPush = vi.fn();
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({
|
||||
push: mockPush,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/services/api", () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/services/productService", () => ({
|
||||
productService: {
|
||||
getProducts: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/store/settingsStore", () => ({
|
||||
useSettingsStore: vi.fn((selector) => {
|
||||
if (typeof selector === "function") {
|
||||
return selector({ getText: (_key: string, def: string) => def });
|
||||
}
|
||||
return { getText: (_key: string, def: string) => def };
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/store/userStore", () => ({
|
||||
useUserStore: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/store/uiStore", () => ({
|
||||
useUIStore: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/store/usePetStore", () => ({
|
||||
usePetStore: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("SmartAdvisor Component (Interactive Questionnaire)", () => {
|
||||
const mockSetLoginModalOpen = vi.fn();
|
||||
const mockAddPet = vi.fn();
|
||||
const mockSetActivePet = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(api.get).mockResolvedValue({ data: [] });
|
||||
|
||||
vi.mocked(useUserStore).mockReturnValue({
|
||||
isLoggedIn: false,
|
||||
} as any);
|
||||
|
||||
vi.mocked(useUIStore).mockImplementation(((selector: any) => {
|
||||
const state = { setLoginModalOpen: mockSetLoginModalOpen };
|
||||
return typeof selector === "function" ? selector(state) : state;
|
||||
}) as any);
|
||||
|
||||
vi.mocked(usePetStore).mockReturnValue({
|
||||
addPet: mockAddPet,
|
||||
setActivePet: mockSetActivePet,
|
||||
pets: [],
|
||||
} as any);
|
||||
});
|
||||
|
||||
it("renders Step 1 with pet type toggles, name and breed input fields", () => {
|
||||
render(<SmartAdvisor />);
|
||||
|
||||
expect(screen.getByText("گام اول: مشخصات پت")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: /سگ/ })).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: /گربه/ })).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText("مثال: لوسی")).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText("مثال: ژرمن شپرد")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("validates Step 1 and displays warning if name or breed is empty", () => {
|
||||
render(<SmartAdvisor />);
|
||||
|
||||
const nextBtn = screen.getByRole("button", { name: /ثبت هویت و ادامه/ });
|
||||
fireEvent.click(nextBtn);
|
||||
|
||||
expect(
|
||||
screen.getByText(/لطفاً ابتدا نام و نژاد پت را وارد کنید/)
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("switches pet species between Dog and Cat in Step 1", () => {
|
||||
render(<SmartAdvisor />);
|
||||
|
||||
const catBtn = screen.getByRole("button", { name: /گربه/ });
|
||||
fireEvent.click(catBtn);
|
||||
|
||||
expect(catBtn.className).toContain("border-canina-blue");
|
||||
});
|
||||
|
||||
it("advances to Step 2 when name and breed are filled", () => {
|
||||
render(<SmartAdvisor />);
|
||||
|
||||
const nameInput = screen.getByPlaceholderText("مثال: لوسی");
|
||||
const breedInput = screen.getByPlaceholderText("مثال: ژرمن شپرد");
|
||||
const nextBtn = screen.getByRole("button", { name: /ثبت هویت و ادامه/ });
|
||||
|
||||
fireEvent.change(nameInput, { target: { value: "تدی" } });
|
||||
fireEvent.change(breedInput, { target: { value: "پودل" } });
|
||||
fireEvent.click(nextBtn);
|
||||
|
||||
expect(screen.getByText("گام دوم: پایش فیزیکی")).toBeInTheDocument();
|
||||
expect(screen.getByText("سن حیوان (سال)")).toBeInTheDocument();
|
||||
expect(screen.getByText("وزن حیوان (کیلوگرم)")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("adjusts age, weight, and activity level in Step 2 and allows going back", () => {
|
||||
render(<SmartAdvisor />);
|
||||
|
||||
// Complete Step 1
|
||||
fireEvent.change(screen.getByPlaceholderText("مثال: لوسی"), { target: { value: "تدی" } });
|
||||
fireEvent.change(screen.getByPlaceholderText("مثال: ژرمن شپرد"), { target: { value: "پودل" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: /ثبت هویت و ادامه/ }));
|
||||
|
||||
expect(screen.getByText("گام دوم: پایش فیزیکی")).toBeInTheDocument();
|
||||
|
||||
// In Step 2, test back button
|
||||
const backBtn = screen.getByRole("button", { name: /قبلی/ });
|
||||
fireEvent.click(backBtn);
|
||||
|
||||
expect(screen.getByText("گام اول: مشخصات پت")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("advances to Step 3 (Symptoms) and toggles specific symptom options", () => {
|
||||
render(<SmartAdvisor />);
|
||||
|
||||
// Step 1
|
||||
fireEvent.change(screen.getByPlaceholderText("مثال: لوسی"), { target: { value: "تدی" } });
|
||||
fireEvent.change(screen.getByPlaceholderText("مثال: ژرمن شپرد"), { target: { value: "پودل" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: /ثبت هویت و ادامه/ }));
|
||||
|
||||
// Step 2
|
||||
const step2Next = screen.getByRole("button", { name: /علائم بالینی/ });
|
||||
fireEvent.click(step2Next);
|
||||
|
||||
expect(screen.getByText("گام سوم: علائم بالینی فعلی")).toBeInTheDocument();
|
||||
expect(screen.getByText(/درد مفاصل و لنگیدن/)).toBeInTheDocument();
|
||||
|
||||
// Select symptom
|
||||
const jointPainOpt = screen.getByText(/درد مفاصل و لنگیدن/);
|
||||
fireEvent.click(jointPainOpt);
|
||||
|
||||
expect(jointPainOpt.closest("button")?.className).toContain("border-canina-blue");
|
||||
});
|
||||
|
||||
it("advances to Step 4 (Medical History) and selects history option", () => {
|
||||
render(<SmartAdvisor />);
|
||||
|
||||
// Step 1
|
||||
fireEvent.change(screen.getByPlaceholderText("مثال: لوسی"), { target: { value: "تدی" } });
|
||||
fireEvent.change(screen.getByPlaceholderText("مثال: ژرمن شپرد"), { target: { value: "پودل" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: /ثبت هویت و ادامه/ }));
|
||||
|
||||
// Step 2
|
||||
fireEvent.click(screen.getByRole("button", { name: /علائم بالینی/ }));
|
||||
|
||||
// Step 3
|
||||
fireEvent.click(screen.getByRole("button", { name: /سوابق پزشکی/ }));
|
||||
|
||||
expect(screen.getByText("گام چهارم: سوابق پزشکی")).toBeInTheDocument();
|
||||
expect(screen.getByText(/سابقه جراحی مفاصل\/استخوان/)).toBeInTheDocument();
|
||||
|
||||
const surgeryOpt = screen.getByText(/سابقه جراحی مفاصل\/استخوان/);
|
||||
fireEvent.click(surgeryOpt);
|
||||
|
||||
expect(surgeryOpt.closest("button")?.className).toContain("border-canina-blue");
|
||||
});
|
||||
|
||||
it("calls onComplete callback with collected profile data if onComplete is provided", async () => {
|
||||
const handleComplete = vi.fn();
|
||||
render(<SmartAdvisor onComplete={handleComplete} />);
|
||||
|
||||
// Step 1
|
||||
fireEvent.change(screen.getByPlaceholderText("مثال: لوسی"), { target: { value: "تدی" } });
|
||||
fireEvent.change(screen.getByPlaceholderText("مثال: ژرمن شپرد"), { target: { value: "پودل" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: /ثبت هویت و ادامه/ }));
|
||||
|
||||
// Step 2
|
||||
fireEvent.click(screen.getByRole("button", { name: /علائم بالینی/ }));
|
||||
|
||||
// Step 3
|
||||
fireEvent.click(screen.getByRole("button", { name: /سوابق پزشکی/ }));
|
||||
|
||||
// Step 4 Submit
|
||||
const submitBtn = screen.getByRole("button", { name: /صدور شناسنامه و پیشنهاد/ });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(handleComplete).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
name: "تدی",
|
||||
breed: "پودل",
|
||||
type: "سگ",
|
||||
age: 3,
|
||||
weight: 10,
|
||||
activityLevel: "متوسط",
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("opens login modal when unauthenticated user submits advisor questionnaire without onComplete", async () => {
|
||||
vi.mocked(useUserStore).mockReturnValue({
|
||||
isLoggedIn: false,
|
||||
} as any);
|
||||
|
||||
render(<SmartAdvisor />);
|
||||
|
||||
// Step 1
|
||||
fireEvent.change(screen.getByPlaceholderText("مثال: لوسی"), { target: { value: "تدی" } });
|
||||
fireEvent.change(screen.getByPlaceholderText("مثال: ژرمن شپرد"), { target: { value: "پودل" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: /ثبت هویت و ادامه/ }));
|
||||
|
||||
// Step 2
|
||||
fireEvent.click(screen.getByRole("button", { name: /علائم بالینی/ }));
|
||||
|
||||
// Step 3
|
||||
fireEvent.click(screen.getByRole("button", { name: /سوابق پزشکی/ }));
|
||||
|
||||
// Step 4 Submit
|
||||
const submitBtn = screen.getByRole("button", { name: /صدور شناسنامه و پیشنهاد/ });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockSetLoginModalOpen).toHaveBeenCalledWith(
|
||||
true,
|
||||
expect.objectContaining({
|
||||
name: "تدی",
|
||||
breed: "پودل",
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("creates pet, sets active pet, and navigates to /profile when authenticated user submits questionnaire", async () => {
|
||||
vi.mocked(useUserStore).mockReturnValue({
|
||||
isLoggedIn: true,
|
||||
} as any);
|
||||
|
||||
render(<SmartAdvisor />);
|
||||
|
||||
// Step 1
|
||||
fireEvent.change(screen.getByPlaceholderText("مثال: لوسی"), { target: { value: "تدی" } });
|
||||
fireEvent.change(screen.getByPlaceholderText("مثال: ژرمن شپرد"), { target: { value: "پودل" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: /ثبت هویت و ادامه/ }));
|
||||
|
||||
// Step 2
|
||||
fireEvent.click(screen.getByRole("button", { name: /علائم بالینی/ }));
|
||||
|
||||
// Step 3
|
||||
fireEvent.click(screen.getByRole("button", { name: /سوابق پزشکی/ }));
|
||||
|
||||
// Step 4 Submit
|
||||
const submitBtn = screen.getByRole("button", { name: /صدور شناسنامه و پیشنهاد/ });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockAddPet).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
name: "تدی",
|
||||
breed: "پودل",
|
||||
})
|
||||
);
|
||||
expect(mockSetActivePet).toHaveBeenCalled();
|
||||
expect(mockPush).toHaveBeenCalledWith("/profile");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import TestimonialsSection from '../TestimonialsSection';
|
||||
import api from '../../lib/services/api';
|
||||
import { useSettingsStore } from '../../lib/store/settingsStore';
|
||||
|
||||
// Mock motion/react
|
||||
vi.mock('motion/react', () => ({
|
||||
motion: {
|
||||
div: ({ children, className, ...props }: any) => <div className={className} {...props}>{children}</div>,
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock SafeImage
|
||||
vi.mock('../SafeImage', () => ({
|
||||
default: ({ src, alt, className }: any) => (
|
||||
<img src={src} alt={alt} className={className} data-testid="safe-image" />
|
||||
),
|
||||
}));
|
||||
|
||||
// Mock api service
|
||||
vi.mock('../../lib/services/api', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
},
|
||||
BASE_DOMAIN: 'https://api.canina.ir',
|
||||
}));
|
||||
|
||||
describe('TestimonialsSection Component', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
useSettingsStore.setState({ texts: {} });
|
||||
});
|
||||
|
||||
it('renders nothing when API returns empty testimonials array', async () => {
|
||||
(api.get as any).mockResolvedValueOnce({ data: [] });
|
||||
|
||||
const { container } = render(<TestimonialsSection />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it('renders nothing gracefully on API error', async () => {
|
||||
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
(api.get as any).mockRejectedValueOnce(new Error('Network error'));
|
||||
|
||||
const { container } = render(<TestimonialsSection />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
consoleErrorSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('renders testimonials correctly when data is nested in data.testimonials and filters out inactive items', async () => {
|
||||
const mockData = {
|
||||
data: {
|
||||
testimonials: [
|
||||
{
|
||||
id: 't-1',
|
||||
authorName: 'دکتر علیرضا کاظمی',
|
||||
roleTitle: 'متخصص جراحی دامپزشکی',
|
||||
avatarUrl: '/uploads/avatars/kazemi.jpg',
|
||||
content: 'کیفیت کلسیم و مفاصل کنینا فوقالعاده است.',
|
||||
rating: 5,
|
||||
isActive: true,
|
||||
isFeatured: true,
|
||||
},
|
||||
{
|
||||
id: 't-2',
|
||||
authorName: 'سارا رضایی',
|
||||
roleTitle: 'سرپرست ژرمن شپرد',
|
||||
avatarUrl: 'https://cdn.example.com/sara.jpg',
|
||||
content: 'پوشش موهای سگم بعد از یک ماه براق شد.',
|
||||
rating: 4,
|
||||
isActive: true,
|
||||
isFeatured: false,
|
||||
},
|
||||
{
|
||||
id: 't-3',
|
||||
authorName: 'کاربر غیرفعال',
|
||||
content: 'این پیام نباید نمایش داده شود.',
|
||||
isActive: false,
|
||||
rating: 5,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
(api.get as any).mockResolvedValueOnce({ data: mockData });
|
||||
|
||||
render(<TestimonialsSection />);
|
||||
|
||||
// Wait for data to load
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('دکتر علیرضا کاظمی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByText('متخصص جراحی دامپزشکی')).toBeInTheDocument();
|
||||
expect(screen.getByText(/کیفیت کلسیم و مفاصل کنینا فوقالعاده است/)).toBeInTheDocument();
|
||||
expect(screen.getByText('سارا رضایی')).toBeInTheDocument();
|
||||
expect(screen.getByText('سرپرست ژرمن شپرد')).toBeInTheDocument();
|
||||
expect(screen.getByText(/پوشش موهای سگم بعد از یک ماه براق شد/)).toBeInTheDocument();
|
||||
|
||||
// Verify inactive testimonial is filtered out
|
||||
expect(screen.queryByText('کاربر غیرفعال')).not.toBeInTheDocument();
|
||||
|
||||
// Check images (relative vs absolute url handling)
|
||||
const images = screen.getAllByTestId('safe-image');
|
||||
expect(images[0]).toHaveAttribute('src', 'https://api.canina.ir/uploads/avatars/kazemi.jpg');
|
||||
expect(images[1]).toHaveAttribute('src', 'https://cdn.example.com/sara.jpg');
|
||||
});
|
||||
|
||||
it('renders fallback icon when testimonial does not have avatarUrl', async () => {
|
||||
const mockData = {
|
||||
testimonials: [
|
||||
{
|
||||
id: 't-no-avatar',
|
||||
authorName: 'مریم احمدی',
|
||||
content: 'تجربه بسیار خوبی در خرید این مکمل داشتم.',
|
||||
rating: 5,
|
||||
isActive: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
(api.get as any).mockResolvedValueOnce({ data: mockData });
|
||||
|
||||
render(<TestimonialsSection />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('مریم احمدی')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.queryByTestId('safe-image')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uses custom titles and badges from useSettingsStore texts', async () => {
|
||||
useSettingsStore.setState({
|
||||
texts: {
|
||||
testimonials_badge: 'دیدگاههای معتبر',
|
||||
testimonials_title_1: 'نظرات و',
|
||||
testimonials_title_2: 'تجارب همکاران',
|
||||
testimonials_desc: 'توضیحات سفارشی درباره نظرات دامپزشکان',
|
||||
},
|
||||
});
|
||||
|
||||
const mockData = [
|
||||
{
|
||||
id: 't-1',
|
||||
authorName: 'دکتر نادری',
|
||||
content: 'عالی بود',
|
||||
rating: 5,
|
||||
isActive: true,
|
||||
},
|
||||
];
|
||||
|
||||
(api.get as any).mockResolvedValueOnce({ data: mockData });
|
||||
|
||||
render(<TestimonialsSection />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('دیدگاههای معتبر')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByText('نظرات و')).toBeInTheDocument();
|
||||
expect(screen.getByText('تجارب همکاران')).toBeInTheDocument();
|
||||
expect(screen.getByText('توضیحات سفارشی درباره نظرات دامپزشکان')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import TickerBanner from '../TickerBanner';
|
||||
import { useSettingsStore } from '../../lib/store/settingsStore';
|
||||
|
||||
describe('TickerBanner Component', () => {
|
||||
beforeEach(() => {
|
||||
useSettingsStore.setState({
|
||||
texts: {
|
||||
shipping_notice: 'ارسال رایگان برای سفارشهای ویژه کنینا',
|
||||
site_logo_text_en: 'Canina',
|
||||
site_logo_text_fa: 'ایران',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('renders announcement text from settingsStore', () => {
|
||||
render(<TickerBanner />);
|
||||
const notices = screen.getAllByText(/ارسال رایگان برای سفارشهای ویژه کنینا/);
|
||||
expect(notices.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('renders default brand title in mobile view when logo is text', () => {
|
||||
render(<TickerBanner />);
|
||||
expect(screen.getByText('Canina')).toBeInTheDocument();
|
||||
expect(screen.getByText('ایران')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,51 +1,60 @@
|
||||
"use client";
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import Tooltip from '../Tooltip';
|
||||
import { useSettingsStore } from '../../lib/store/settingsStore';
|
||||
|
||||
vi.mock('../../lib/store/settingsStore', () => ({
|
||||
useSettingsStore: vi.fn(),
|
||||
vi.mock('motion/react', () => ({
|
||||
motion: {
|
||||
div: ({ children, className, onClick }: any) => (
|
||||
<div className={className} onClick={onClick}>
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
AnimatePresence: ({ children }: any) => <>{children}</>,
|
||||
}));
|
||||
|
||||
describe('Tooltip', () => {
|
||||
it('should render children correctly', () => {
|
||||
vi.mocked(useSettingsStore).mockReturnValue({});
|
||||
vi.mock('../../lib/store/settingsStore', () => ({
|
||||
useSettingsStore: () => ({
|
||||
glucosamine: {
|
||||
term: 'گلوکوزامین',
|
||||
definition: 'ترکیب طبیعی ضروری برای حفظ غضروفها',
|
||||
wikiId: 'glucosamine-wiki',
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
render(
|
||||
<Tooltip termKey="mussel">
|
||||
<span>Mussel Term</span>
|
||||
</Tooltip>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Mussel Term')).toBeInTheDocument();
|
||||
describe('Tooltip Component', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should display tooltip definition on hover', async () => {
|
||||
const mockTerms = {
|
||||
mussel: {
|
||||
key: 'mussel',
|
||||
term: 'Green Mussel',
|
||||
definition: 'Scientific definition of NZ green mussel',
|
||||
wikiId: 'green-mussel',
|
||||
},
|
||||
};
|
||||
vi.mocked(useSettingsStore).mockReturnValue(mockTerms);
|
||||
it('renders children normally', () => {
|
||||
render(<Tooltip termKey="glucosamine">توضیح گلوکوزامین</Tooltip>);
|
||||
expect(screen.getByText('توضیح گلوکوزامین')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows tooltip content on click', () => {
|
||||
render(<Tooltip termKey="glucosamine">توضیح گلوکوزامین</Tooltip>);
|
||||
const trigger = screen.getByText('توضیح گلوکوزامین');
|
||||
fireEvent.click(trigger);
|
||||
|
||||
expect(screen.getByText('دانشنامه علمی کنینا')).toBeInTheDocument();
|
||||
expect(screen.getByText('گلوکوزامین')).toBeInTheDocument();
|
||||
expect(screen.getByText('ترکیب طبیعی ضروری برای حفظ غضروفها')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('triggers onWikiNavigate when article link is clicked', () => {
|
||||
const onWikiNavigate = vi.fn();
|
||||
render(
|
||||
<Tooltip termKey="mussel">
|
||||
<span>Hover Me</span>
|
||||
</Tooltip>
|
||||
<Tooltip termKey="glucosamine" onWikiNavigate={onWikiNavigate}>
|
||||
توضیح گلوکوزامین
|
||||
</Tooltip>,
|
||||
);
|
||||
fireEvent.click(screen.getByText('توضیح گلوکوزامین'));
|
||||
|
||||
const trigger = screen.getByText('Hover Me');
|
||||
fireEvent.mouseEnter(trigger);
|
||||
const wikiBtn = screen.getByText('مطالعه مقاله کامل');
|
||||
fireEvent.click(wikiBtn);
|
||||
|
||||
expect(screen.getByText('Green Mussel')).toBeInTheDocument();
|
||||
expect(screen.getByText('Scientific definition of NZ green mussel')).toBeInTheDocument();
|
||||
|
||||
fireEvent.mouseLeave(trigger);
|
||||
// Tooltip should exit (though animations might delay actual removal, under standard RTL fireEvent it updates state immediately)
|
||||
expect(onWikiNavigate).toHaveBeenCalledWith('glucosamine-wiki');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,219 @@
|
||||
"use client";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import TopUpModal from "../TopUpModal";
|
||||
import { useUserStore } from "../../lib/store/userStore";
|
||||
import { useSettingsStore } from "../../lib/store/settingsStore";
|
||||
import api from "../../lib/services/api";
|
||||
import { toast } from "sonner";
|
||||
|
||||
vi.mock("../../lib/store/userStore", () => ({
|
||||
useUserStore: Object.assign(vi.fn(), {
|
||||
getState: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/store/settingsStore", () => ({
|
||||
useSettingsStore: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/services/api", () => ({
|
||||
default: {
|
||||
post: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("sonner", () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("TopUpModal Component", () => {
|
||||
const mockOnClose = vi.fn();
|
||||
const mockOnConfirm = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
vi.mocked(useUserStore).mockReturnValue({
|
||||
isLoggedIn: true,
|
||||
profile: { mobile: "09121234567" },
|
||||
} as any);
|
||||
|
||||
(useUserStore as any).getState = vi.fn(() => ({
|
||||
isLoggedIn: true,
|
||||
}));
|
||||
|
||||
vi.mocked(useSettingsStore).mockImplementation((selector: any) => {
|
||||
return selector({
|
||||
getBoolean: vi.fn((key: string, def: boolean) => def),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("does not render when isOpen is false", () => {
|
||||
const { container } = render(
|
||||
<TopUpModal isOpen={false} onClose={mockOnClose} />
|
||||
);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it("renders modal with header and preset buttons when isOpen is true", () => {
|
||||
render(<TopUpModal isOpen={true} onClose={mockOnClose} />);
|
||||
|
||||
expect(screen.getByText("شارژ آنلاین کیف پول")).toBeInTheDocument();
|
||||
expect(screen.getByText("۵۰۰,۰۰۰ تومان")).toBeInTheDocument();
|
||||
expect(screen.getByText("۱,۰۰۰,۰۰۰ تومان")).toBeInTheDocument();
|
||||
expect(screen.getByText("۲,۰۰۰,۰۰۰ تومان")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("populates initial amount if provided in props", () => {
|
||||
render(
|
||||
<TopUpModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
initialAmount={350000}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByDisplayValue("350,000")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("selects preset amount when preset button is clicked", () => {
|
||||
render(<TopUpModal isOpen={true} onClose={mockOnClose} />);
|
||||
|
||||
const preset1m = screen.getByText("۱,۰۰۰,۰۰۰ تومان");
|
||||
fireEvent.click(preset1m);
|
||||
|
||||
expect(screen.getByDisplayValue("1,000,000")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("allows custom amount manual typing", () => {
|
||||
render(<TopUpModal isOpen={true} onClose={mockOnClose} />);
|
||||
|
||||
const input = screen.getByPlaceholderText("۰");
|
||||
fireEvent.change(input, { target: { value: "750000" } });
|
||||
|
||||
expect(screen.getByDisplayValue("750,000")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("blocks submission and shows error if user is not logged in", async () => {
|
||||
(useUserStore as any).getState = vi.fn(() => ({
|
||||
isLoggedIn: false,
|
||||
}));
|
||||
|
||||
render(
|
||||
<TopUpModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
initialAmount={100000}
|
||||
/>
|
||||
);
|
||||
|
||||
const submitBtn = screen.getByRole("button", { name: /اتصال به درگاه و شارژ آنلاین/ });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
expect(toast.error).toHaveBeenCalledWith(
|
||||
"جهت افزایش موجودی کیف پول لطفاً ابتدا وارد حساب کاربری خود شوید."
|
||||
);
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("validates minimum amount (at least 10,000 Tomans)", async () => {
|
||||
render(<TopUpModal isOpen={true} onClose={mockOnClose} />);
|
||||
|
||||
const input = screen.getByPlaceholderText("۰");
|
||||
fireEvent.change(input, { target: { value: "5000" } });
|
||||
|
||||
const submitBtn = screen.getByRole("button", { name: /اتصال به درگاه و شارژ آنلاین/ });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
expect(toast.error).toHaveBeenCalledWith("حداقل مبلغ شارژ ۱۰,۰۰۰ تومان است");
|
||||
expect(api.post).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("submits payment request and redirects to gateway paymentUrl on success", async () => {
|
||||
const originalLocation = window.location;
|
||||
// mock window.location
|
||||
delete (window as any).location;
|
||||
window.location = { ...originalLocation, href: "" } as any;
|
||||
|
||||
vi.mocked(api.post).mockResolvedValueOnce({
|
||||
data: {
|
||||
success: true,
|
||||
paymentUrl: "https://gateway.zibal.ir/start/12345678",
|
||||
},
|
||||
});
|
||||
|
||||
render(
|
||||
<TopUpModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
initialAmount={500000}
|
||||
/>
|
||||
);
|
||||
|
||||
const submitBtn = screen.getByRole("button", { name: /اتصال به درگاه و شارژ آنلاین/ });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.post).toHaveBeenCalledWith("/payment/zibal/wallet/initiate", {
|
||||
amount: 500000,
|
||||
});
|
||||
expect(toast.success).toHaveBeenCalledWith("در حال انتقال امن به درگاه پرداخت زیبال...");
|
||||
expect(window.location.href).toBe("https://gateway.zibal.ir/start/12345678");
|
||||
});
|
||||
|
||||
window.location = originalLocation;
|
||||
});
|
||||
|
||||
it("handles payment gateway initialization failure", async () => {
|
||||
vi.mocked(api.post).mockResolvedValueOnce({
|
||||
data: { success: false, paymentUrl: null },
|
||||
});
|
||||
|
||||
render(
|
||||
<TopUpModal
|
||||
isOpen={true}
|
||||
onClose={mockOnClose}
|
||||
initialAmount={500000}
|
||||
/>
|
||||
);
|
||||
|
||||
const submitBtn = screen.getByRole("button", { name: /اتصال به درگاه و شارژ آنلاین/ });
|
||||
fireEvent.click(submitBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(toast.error).toHaveBeenCalledWith("خطا در ایجاد تراکنش درگاه پرداخت زیبال");
|
||||
});
|
||||
});
|
||||
|
||||
it("shows card-to-card account details when card-to-card setting is enabled", () => {
|
||||
vi.mocked(useSettingsStore).mockImplementation((selector: any) => {
|
||||
return selector({
|
||||
getBoolean: vi.fn((key: string) => key === "payment_card_to_card_enabled"),
|
||||
});
|
||||
});
|
||||
|
||||
render(<TopUpModal isOpen={true} onClose={mockOnClose} />);
|
||||
|
||||
expect(screen.getByText("اطلاعات کارت جهت واریز کارتبهکارت:")).toBeInTheDocument();
|
||||
expect(screen.getByText(/۶۲۱۹-۸۶۱۹-۷۴۰۱-۲۰۷۱/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/IR-65 0560 6118 2800 5725 1015 01/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("calls onClose when close button is clicked", () => {
|
||||
render(<TopUpModal isOpen={true} onClose={mockOnClose} />);
|
||||
|
||||
// Top X close button
|
||||
const closeButtons = screen.getAllByRole("button");
|
||||
const closeIconBtn = closeButtons.find(b => b.querySelector("svg.lucide-x"));
|
||||
expect(closeIconBtn).toBeDefined();
|
||||
|
||||
fireEvent.click(closeIconBtn!);
|
||||
expect(mockOnClose).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import React from 'react';
|
||||
import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react';
|
||||
const h = vi.hoisted(() => ({ push: vi.fn(), back: vi.fn(), replace: vi.fn() }));
|
||||
vi.mock('next/navigation', () => ({ useRouter: () => h, useSearchParams: () => new URLSearchParams(window.location.search) }));
|
||||
vi.mock('motion/react', async () => {
|
||||
const R = await import('react'); const cache: Record<string, React.ComponentType<any>> = {};
|
||||
return { AnimatePresence: ({children}: any) => children, motion: new Proxy({}, { get: (_, tag: string) => cache[tag] ||= R.forwardRef(({children, ...props}: any, ref) => {
|
||||
const clean = Object.fromEntries(Object.entries(props).filter(([k]) => !['initial','animate','exit','transition','whileHover','whileTap','whileInView','viewport','layout','layoutId','drag','dragConstraints','dragElastic','onDragEnd'].includes(k)));
|
||||
return R.createElement(tag, {...clean, ref}, children);
|
||||
}) }) };
|
||||
});
|
||||
vi.mock('next/image', () => ({ default: ({unoptimized, priority, fill, ...props}: any) => <img {...props} /> }));
|
||||
vi.mock('sonner', () => ({ toast: {success: vi.fn(), error: vi.fn(), info: vi.fn()} }));
|
||||
import { toast } from 'sonner';
|
||||
afterEach(cleanup);
|
||||
import UserDashboard from '../UserDashboard';
|
||||
const state=vi.hoisted(()=>({logged:true,profile:{firstName:'Test',lastName:'User',email:'test@example.test',mobile:'09120000000',hasPassword:false,addresses:[],transactions:[],walletBalance:0},updateProfile:vi.fn(),fetchProfile:vi.fn(),logout:vi.fn(),catalog:{isCatalogOnly:false,showOrders:true,showWallet:true,showCharity:true}}));
|
||||
vi.mock('../../lib/store/userStore',()=>{const useUserStore=Object.assign(()=>({profile:state.profile,isLoggedIn:state.logged,updateProfile:state.updateProfile,fetchProfile:state.fetchProfile,logout:state.logout}),{getState:()=>({fetchProfile:state.fetchProfile})});return {useUserStore};});
|
||||
vi.mock('../../lib/store/cartStore',()=>({useCartStore:()=>({orders:[]})}));
|
||||
vi.mock('../../lib/store/usePetStore',()=>({usePetStore:()=>({pets:[]})}));
|
||||
vi.mock('../../lib/store/settingsStore',()=>({useSettingsStore:(s:any)=>s({getBoolean:(_:string,d:boolean)=>d,getText:(_:string,d:string)=>d})}));
|
||||
vi.mock('../../lib/useCatalogMode',()=>({useCatalogMode:()=>state.catalog}));
|
||||
vi.mock('../../lib/services/api',()=>({default:{get:vi.fn().mockResolvedValue({data:[]})},BASE_DOMAIN:'https://example.test'}));
|
||||
vi.mock('../../lib/services/ticketService',()=>({ticketService:{getMyTickets:vi.fn(),createTicket:vi.fn()}}));
|
||||
import { ticketService } from '../../lib/services/ticketService';
|
||||
beforeEach(()=>{vi.clearAllMocks();window.history.replaceState(null,'','/dashboard');state.logged=true;state.catalog={isCatalogOnly:false,showOrders:true,showWallet:true,showCharity:true};state.updateProfile.mockResolvedValue(undefined);state.fetchProfile.mockResolvedValue(undefined);vi.mocked(ticketService.getMyTickets).mockResolvedValue([]);});
|
||||
describe('UserDashboard',()=>{
|
||||
it('redirects anonymous visitors without rendering private data',()=>{state.logged=false;const {container}=render(<UserDashboard/>);expect(container).toBeEmptyDOMElement();expect(h.push).toHaveBeenCalledWith('/');expect(toast.error).toHaveBeenCalledWith('برای دسترسی به داشبورد لطفاً ابتدا وارد حساب کاربری خود شوید.');});
|
||||
it('blocks orders and wallet deep links when catalog permissions disable tabs',()=>{state.catalog={isCatalogOnly:true,showOrders:false,showWallet:false,showCharity:false};window.history.replaceState(null,'','/dashboard?tab=wallet');render(<UserDashboard/>);expect(screen.queryByRole('button',{name:'کیف پول'})).not.toBeInTheDocument();expect(screen.queryByRole('button',{name:'سفارشات من'})).not.toBeInTheDocument();expect(screen.getByDisplayValue('Test')).toHaveAttribute('readonly');});
|
||||
it('refreshes orders, shows empty state and routes to shop',async()=>{window.history.replaceState(null,'','/dashboard?tab=orders');render(<UserDashboard/>);await screen.findByText('هنوز سفارشی ثبت نکردهاید.');expect(state.fetchProfile).toHaveBeenCalledTimes(1);fireEvent.click(screen.getByRole('button',{name:'برو به فروشگاه'}));expect(h.push).toHaveBeenCalledWith('/shop');});
|
||||
it('rejects mismatched passwords before updating profile',()=>{render(<UserDashboard/>);fireEvent.change(screen.getByPlaceholderText('حداقل ۶ کاراکتر'),{target:{value:'test-only-a'}});fireEvent.change(screen.getByPlaceholderText('تکرار رمز عبور'),{target:{value:'test-only-b'}});fireEvent.click(screen.getByRole('button',{name:'ثبت رمز عبور'}));expect(toast.error).toHaveBeenCalledWith('رمز عبور جدید و تکرار آن یکسان نیستند');expect(state.updateProfile).not.toHaveBeenCalled();});
|
||||
it('keeps password action disabled below minimum length',()=>{render(<UserDashboard/>);fireEvent.change(screen.getByPlaceholderText('حداقل ۶ کاراکتر'),{target:{value:'short'}});fireEvent.change(screen.getByPlaceholderText('تکرار رمز عبور'),{target:{value:'short'}});expect(screen.getByRole('button',{name:'ثبت رمز عبور'})).toBeDisabled();expect(state.updateProfile).not.toHaveBeenCalled();});
|
||||
it('retains password input after save failure and allows retry',async()=>{
|
||||
state.updateProfile.mockRejectedValueOnce(new Error('Account update unavailable'));
|
||||
render(<UserDashboard/>);
|
||||
fireEvent.change(screen.getByPlaceholderText('حداقل ۶ کاراکتر'),{target:{value:'test-only-password'}});
|
||||
fireEvent.change(screen.getByPlaceholderText('تکرار رمز عبور'),{target:{value:'test-only-password'}});
|
||||
fireEvent.click(screen.getByRole('button',{name:'ثبت رمز عبور'}));
|
||||
await waitFor(()=>expect(toast.error).toHaveBeenCalledWith('Account update unavailable'));
|
||||
expect(screen.getByPlaceholderText('حداقل ۶ کاراکتر')).toHaveValue('test-only-password');
|
||||
expect(screen.getByRole('button',{name:'ثبت رمز عبور'})).not.toBeDisabled();
|
||||
fireEvent.click(screen.getByRole('button',{name:'ثبت رمز عبور'}));
|
||||
await waitFor(()=>expect(toast.success).toHaveBeenCalledWith('رمز عبور با موفقیت برای حساب شما ثبت شد'));
|
||||
expect(screen.getByPlaceholderText('حداقل ۶ کاراکتر')).toHaveValue('');
|
||||
expect(state.updateProfile).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it('reports ticket fetch errors and clears loading',async()=>{window.history.replaceState(null,'','/dashboard?tab=tickets');vi.mocked(ticketService.getMyTickets).mockRejectedValueOnce(new Error('offline'));render(<UserDashboard/>);await waitFor(()=>expect(toast.error).toHaveBeenCalledWith('خطا در دریافت لیست تیکتها'));expect(ticketService.getMyTickets).toHaveBeenCalledTimes(1);});
|
||||
});
|
||||
@@ -0,0 +1,179 @@
|
||||
import React from "react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||
import VetGallery from "../VetGallery";
|
||||
import { videoService } from "../../lib/services/videoService";
|
||||
|
||||
// Mock motion/react
|
||||
vi.mock("motion/react", () => ({
|
||||
AnimatePresence: ({ children }: { children: React.ReactNode }) => <>{children}</>,
|
||||
motion: {
|
||||
button: ({ children, onClick, className, ...props }: any) => (
|
||||
<button onClick={onClick} className={className} {...props}>
|
||||
{children}
|
||||
</button>
|
||||
),
|
||||
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" />
|
||||
),
|
||||
}));
|
||||
|
||||
// Mock VideoModalPlayer
|
||||
vi.mock("../VideoModalPlayer", () => ({
|
||||
default: ({ isOpen, onClose, video }: { isOpen: boolean; onClose: () => void; video: any }) => (
|
||||
isOpen && video ? (
|
||||
<div data-testid="video-modal-player">
|
||||
<span>مدال ویدیو: {video.title}</span>
|
||||
<span>پزشک: {video.doctor}</span>
|
||||
<button onClick={onClose} data-testid="close-video-modal">
|
||||
بستن مدال
|
||||
</button>
|
||||
</div>
|
||||
) : null
|
||||
),
|
||||
}));
|
||||
|
||||
// Mock settingsStore
|
||||
vi.mock("../../lib/store/settingsStore", () => ({
|
||||
useSettingsStore: (selector: any) =>
|
||||
selector({
|
||||
getText: (key: string, fallback: string) => fallback,
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock videoService
|
||||
vi.mock("../../lib/services/videoService", () => ({
|
||||
videoService: {
|
||||
getVideos: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockVideos = [
|
||||
{
|
||||
id: "v-1",
|
||||
title: "نحوه آمادهسازی کانیهیدروکس GAG",
|
||||
doctor: "دکتر کلاوس هنینگ",
|
||||
duration: "۰۱:۴۵",
|
||||
thumbnail: "https://example.com/thumb1.jpg",
|
||||
videoUrl: "https://example.com/video1.mp4",
|
||||
description: "آموزش گام به گام آمادهسازی پودر Canhydrox GAG",
|
||||
},
|
||||
{
|
||||
id: "v-2",
|
||||
title: "اهمیت صدف لبسبز برای غضروفها",
|
||||
doctor: "دکتر النا اشمیت",
|
||||
duration: "۰۲:۲۰",
|
||||
thumbnail: "https://example.com/thumb2.jpg",
|
||||
videoUrl: "https://example.com/video2.mp4",
|
||||
description: "نقش صدف لبسبز در سلامت مفصل سگ و گربه",
|
||||
},
|
||||
];
|
||||
|
||||
describe("VetGallery Component", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("renders nothing when API returns no videos", async () => {
|
||||
vi.mocked(videoService.getVideos).mockResolvedValueOnce([]);
|
||||
|
||||
const { container } = render(<VetGallery />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(videoService.getVideos).toHaveBeenCalledWith({ featured: true, limit: 3 });
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it("handles API rejection gracefully by rendering null", async () => {
|
||||
vi.mocked(videoService.getVideos).mockRejectedValueOnce(new Error("Network Error"));
|
||||
|
||||
const { container } = render(<VetGallery />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it("renders header badge, title, link, and video list when videos are fetched", async () => {
|
||||
vi.mocked(videoService.getVideos).mockResolvedValueOnce(mockVideos);
|
||||
|
||||
render(<VetGallery />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("مشاوره ویدئویی")).toBeInTheDocument();
|
||||
expect(screen.getByText("دوست دامپزشک پت شما")).toBeInTheDocument();
|
||||
expect(screen.getByText("نحوه آمادهسازی کانیهیدروکس GAG")).toBeInTheDocument();
|
||||
expect(screen.getByText("دکتر کلاوس هنینگ")).toBeInTheDocument();
|
||||
expect(screen.getByText("۰۱:۴۵")).toBeInTheDocument();
|
||||
expect(screen.getByText("اهمیت صدف لبسبز برای غضروفها")).toBeInTheDocument();
|
||||
expect(screen.getByText("دکتر النا اشمیت")).toBeInTheDocument();
|
||||
expect(screen.getByText("۰۲:۲۰")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const viewAllLink = screen.getByRole("link", { name: /مشاهده همه ویدئوها/ });
|
||||
expect(viewAllLink).toHaveAttribute("href", "/videos");
|
||||
});
|
||||
|
||||
it("opens video player modal when a video item card is clicked and closes it upon request", async () => {
|
||||
vi.mocked(videoService.getVideos).mockResolvedValueOnce(mockVideos);
|
||||
|
||||
render(<VetGallery />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("نحوه آمادهسازی کانیهیدروکس GAG")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.queryByTestId("video-modal-player")).not.toBeInTheDocument();
|
||||
|
||||
// Click first video card
|
||||
const firstVideoCard = screen.getByText("نحوه آمادهسازی کانیهیدروکس GAG").closest("button");
|
||||
expect(firstVideoCard).not.toBeNull();
|
||||
fireEvent.click(firstVideoCard!);
|
||||
|
||||
// Modal should now be open with details
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("video-modal-player")).toBeInTheDocument();
|
||||
expect(screen.getByText("مدال ویدیو: نحوه آمادهسازی کانیهیدروکس GAG")).toBeInTheDocument();
|
||||
expect(screen.getByText("پزشک: دکتر کلاوس هنینگ")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Close modal
|
||||
const closeBtn = screen.getByTestId("close-video-modal");
|
||||
fireEvent.click(closeBtn);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByTestId("video-modal-player")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("shows fallback doctor name when doctor field is empty", async () => {
|
||||
const videoWithoutDoctor = [
|
||||
{
|
||||
id: "v-3",
|
||||
title: "نکات نگهداری در فصل تابستان",
|
||||
doctor: "",
|
||||
duration: "۰۳:۰۰",
|
||||
thumbnail: "https://example.com/thumb3.jpg",
|
||||
videoUrl: "https://example.com/video3.mp4",
|
||||
},
|
||||
];
|
||||
vi.mocked(videoService.getVideos).mockResolvedValueOnce(videoWithoutDoctor as any);
|
||||
|
||||
render(<VetGallery />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("نکات نگهداری در فصل تابستان")).toBeInTheDocument();
|
||||
expect(screen.getByText("کادر علمی کنینا")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,189 @@
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, act } from '@testing-library/react';
|
||||
import VideoModalPlayer from '../VideoModalPlayer';
|
||||
|
||||
// Mock getMediaUrl helper
|
||||
vi.mock('../../lib/media', () => ({
|
||||
getMediaUrl: (url: string) => url,
|
||||
}));
|
||||
|
||||
describe('VideoModalPlayer Component', () => {
|
||||
const mockVideo = {
|
||||
id: 'vid-123',
|
||||
title: 'آموزش تقویت مفاصل سگهای ژرمن',
|
||||
doctor: 'دکتر علیرضا محمدی',
|
||||
videoUrl: 'https://canina.ir/videos/german-joints.mp4',
|
||||
thumbnail: 'https://canina.ir/images/thumbnail.jpg',
|
||||
description: 'در این ویدیو به بررسی تخصصی ترکیبات گلوکوزامین و کندرویتین پرداخته میشود.',
|
||||
};
|
||||
|
||||
const mockOnClose = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
localStorage.clear();
|
||||
|
||||
// Mock HTMLMediaElement methods in JSDOM
|
||||
window.HTMLMediaElement.prototype.play = vi.fn().mockImplementation(() => Promise.resolve());
|
||||
window.HTMLMediaElement.prototype.pause = vi.fn();
|
||||
window.HTMLMediaElement.prototype.load = vi.fn();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('does not render anything when isOpen is false', () => {
|
||||
const { container } = render(
|
||||
<VideoModalPlayer isOpen={false} onClose={mockOnClose} video={mockVideo} />
|
||||
);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('does not render anything when video is null', () => {
|
||||
const { container } = render(
|
||||
<VideoModalPlayer isOpen={true} onClose={mockOnClose} video={null} />
|
||||
);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('renders video details, doctor, description, and controls when isOpen is true', () => {
|
||||
render(
|
||||
<VideoModalPlayer isOpen={true} onClose={mockOnClose} video={mockVideo} />
|
||||
);
|
||||
|
||||
expect(screen.getByText('آموزش تقویت مفاصل سگهای ژرمن')).toBeInTheDocument();
|
||||
expect(screen.getByText('دکتر علیرضا محمدی')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText('در این ویدیو به بررسی تخصصی ترکیبات گلوکوزامین و کندرویتین پرداخته میشود.')
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByTitle('توقف')).toBeInTheDocument(); // Initially playing
|
||||
expect(screen.getByTitle('بستن')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onClose when close button is clicked', () => {
|
||||
render(
|
||||
<VideoModalPlayer isOpen={true} onClose={mockOnClose} video={mockVideo} />
|
||||
);
|
||||
|
||||
const closeButton = screen.getByTitle('بستن');
|
||||
fireEvent.click(closeButton);
|
||||
|
||||
expect(mockOnClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('toggles play/pause state when play button is clicked', () => {
|
||||
const { container } = render(
|
||||
<VideoModalPlayer isOpen={true} onClose={mockOnClose} video={mockVideo} />
|
||||
);
|
||||
|
||||
const videoEl = container.querySelector('video') as HTMLVideoElement;
|
||||
expect(videoEl).toBeInTheDocument();
|
||||
|
||||
// In jsdom paused defaults to true unless defined.
|
||||
// If paused is true, togglePlay calls videoRef.current.play()
|
||||
const playSpy = vi.spyOn(videoEl, 'play');
|
||||
const pauseSpy = vi.spyOn(videoEl, 'pause');
|
||||
|
||||
// Currently videoEl.paused is true
|
||||
const toggleButton = screen.getByTitle('توقف');
|
||||
fireEvent.click(toggleButton);
|
||||
expect(playSpy).toHaveBeenCalled();
|
||||
|
||||
// Simulate video playing
|
||||
Object.defineProperty(videoEl, 'paused', { value: false, configurable: true });
|
||||
fireEvent.click(toggleButton);
|
||||
expect(pauseSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('allows jumping forward and backward in time', () => {
|
||||
const { container } = render(
|
||||
<VideoModalPlayer isOpen={true} onClose={mockOnClose} video={mockVideo} />
|
||||
);
|
||||
|
||||
const videoEl = container.querySelector('video') as HTMLVideoElement;
|
||||
Object.defineProperty(videoEl, 'duration', { value: 120, configurable: true });
|
||||
videoEl.currentTime = 30;
|
||||
|
||||
const skipForward = screen.getByTitle('۱۰ ثانیه جلو');
|
||||
const skipBackward = screen.getByTitle('۱۰ ثانیه عقب');
|
||||
|
||||
fireEvent.click(skipForward);
|
||||
expect(videoEl.currentTime).toBe(40);
|
||||
|
||||
fireEvent.click(skipBackward);
|
||||
expect(videoEl.currentTime).toBe(30);
|
||||
});
|
||||
|
||||
it('allows toggling mute and volume change', () => {
|
||||
const { container } = render(
|
||||
<VideoModalPlayer isOpen={true} onClose={mockOnClose} video={mockVideo} />
|
||||
);
|
||||
|
||||
const videoEl = container.querySelector('video') as HTMLVideoElement;
|
||||
const muteBtn = screen.getByTitle('بیصدا');
|
||||
fireEvent.click(muteBtn);
|
||||
expect(videoEl.muted).toBe(true);
|
||||
expect(screen.getByTitle('صدا وصل')).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByTitle('صدا وصل'));
|
||||
expect(videoEl.muted).toBe(false);
|
||||
expect(screen.getByTitle('بیصدا')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens playback rate menu and updates rate', () => {
|
||||
const { container } = render(
|
||||
<VideoModalPlayer isOpen={true} onClose={mockOnClose} video={mockVideo} />
|
||||
);
|
||||
|
||||
const videoEl = container.querySelector('video') as HTMLVideoElement;
|
||||
const rateBtn = screen.getByTitle('سرعت پخش');
|
||||
expect(rateBtn).toHaveTextContent('1x');
|
||||
|
||||
fireEvent.click(rateBtn);
|
||||
const speed15 = screen.getByRole('button', { name: '1.5x' });
|
||||
fireEvent.click(speed15);
|
||||
|
||||
expect(rateBtn).toHaveTextContent('1.5x');
|
||||
expect(videoEl.playbackRate).toBe(1.5);
|
||||
});
|
||||
|
||||
it('renders iframe embed when videoUrl contains iframe tag', () => {
|
||||
const iframeVideo = {
|
||||
...mockVideo,
|
||||
videoUrl: '<iframe src="https://www.aparat.com/video/video/embed/videohash/abc123/vt/frame"></iframe>',
|
||||
};
|
||||
|
||||
render(
|
||||
<VideoModalPlayer isOpen={true} onClose={mockOnClose} video={iframeVideo} />
|
||||
);
|
||||
|
||||
const closeBtn = screen.getByTitle('بستن');
|
||||
expect(closeBtn).toBeInTheDocument();
|
||||
fireEvent.click(closeBtn);
|
||||
expect(mockOnClose).toHaveBeenCalledTimes(1);
|
||||
|
||||
expect(document.querySelector('iframe')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shares or copies link when share button is clicked', async () => {
|
||||
const writeTextMock = vi.fn().mockResolvedValue(undefined);
|
||||
Object.assign(navigator, {
|
||||
clipboard: {
|
||||
writeText: writeTextMock,
|
||||
},
|
||||
});
|
||||
|
||||
render(
|
||||
<VideoModalPlayer isOpen={true} onClose={mockOnClose} video={mockVideo} />
|
||||
);
|
||||
|
||||
const shareBtn = screen.getByTitle('اشتراکگذاری');
|
||||
await act(async () => {
|
||||
fireEvent.click(shareBtn);
|
||||
});
|
||||
|
||||
expect(writeTextMock).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import React from 'react';
|
||||
import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react';
|
||||
const h = vi.hoisted(() => ({ push: vi.fn(), back: vi.fn(), replace: vi.fn() }));
|
||||
vi.mock('next/navigation', () => ({ useRouter: () => h, useSearchParams: () => new URLSearchParams(window.location.search) }));
|
||||
vi.mock('motion/react', async () => {
|
||||
const R = await import('react'); const cache: Record<string, React.ComponentType<any>> = {};
|
||||
return { AnimatePresence: ({children}: any) => children, motion: new Proxy({}, { get: (_, tag: string) => cache[tag] ||= R.forwardRef(({children, ...props}: any, ref) => {
|
||||
const clean = Object.fromEntries(Object.entries(props).filter(([k]) => !['initial','animate','exit','transition','whileHover','whileTap','whileInView','viewport','layout','layoutId','drag','dragConstraints','dragElastic','onDragEnd'].includes(k)));
|
||||
return R.createElement(tag, {...clean, ref}, children);
|
||||
}) }) };
|
||||
});
|
||||
vi.mock('next/image', () => ({ default: ({unoptimized, priority, fill, ...props}: any) => <img {...props} /> }));
|
||||
vi.mock('sonner', () => ({ toast: {success: vi.fn(), error: vi.fn(), info: vi.fn()} }));
|
||||
import { toast } from 'sonner';
|
||||
afterEach(cleanup);
|
||||
import VideosPage from '../VideosPage';
|
||||
import { videoService } from '../../lib/services/videoService';
|
||||
vi.mock('../../lib/services/videoService',()=>({videoService:{getVideos:vi.fn(),incrementViews:vi.fn()}}));
|
||||
const videos=[{id:'1',title:'Joint care',doctor:'Dr Alpha',description:'Mobility',thumbnail:'/a.png',videoUrl:'/a.mp4'},{id:'2',title:'Skin care',doctor:'Dr Beta',description:'Coat',thumbnail:'/b.png',videoUrl:'/b.mp4'}];
|
||||
beforeEach(()=>{vi.clearAllMocks();vi.mocked(videoService.getVideos).mockResolvedValue(videos as any);});
|
||||
describe('VideosPage',()=>{
|
||||
it('shows six skeletons until loading completes',async()=>{let resolve!:(v:any)=>void;vi.mocked(videoService.getVideos).mockReturnValueOnce(new Promise(r=>{resolve=r;}));const {container}=render(<VideosPage/>);expect(container.querySelectorAll('.animate-pulse')).toHaveLength(6);resolve(videos);await screen.findByText('Joint care');expect(container.querySelectorAll('.animate-pulse.space-y-4')).toHaveLength(0);expect(videoService.getVideos).toHaveBeenCalledWith({limit:100});});
|
||||
it.each(['JOINT','alpha','mobility'])('filters field %s',async term=>{render(<VideosPage/>);await screen.findByText('Joint care');fireEvent.change(screen.getByPlaceholderText('جستجو در ویدئوهای آموزشی...'),{target:{value:term}});expect(screen.getByText('Joint care')).toBeInTheDocument();expect(screen.queryByText('Skin care')).not.toBeInTheDocument();});
|
||||
it('opens selected video and records its view',async()=>{render(<VideosPage/>);fireEvent.click(await screen.findByText('Joint care'));expect(videoService.incrementViews).toHaveBeenCalledExactlyOnceWith('1');expect(document.querySelector('video')).toHaveAttribute('src','/a.mp4');});
|
||||
it.each([[],null])('handles empty or malformed response %s',async result=>{vi.mocked(videoService.getVideos).mockResolvedValueOnce(result as any);render(<VideosPage/>);expect(await screen.findByText('ویدئویی یافت نشد')).toBeInTheDocument();});
|
||||
it('handles request rejection',async()=>{const err=vi.spyOn(console,'error').mockImplementation(()=>{});vi.mocked(videoService.getVideos).mockRejectedValueOnce(new Error('offline'));render(<VideosPage/>);await screen.findByText('ویدئویی یافت نشد');expect(err).toHaveBeenCalled();err.mockRestore();});
|
||||
it('shares current URL through clipboard',async()=>{const writeText=vi.fn().mockResolvedValue(undefined);Object.defineProperty(navigator,'clipboard',{configurable:true,value:{writeText}});render(<VideosPage/>);await screen.findByText('Joint care');fireEvent.click(screen.getByRole('button',{name:'اشتراکگذاری صفحه'}));expect(writeText).toHaveBeenCalledWith(window.location.href);expect(toast.success).toHaveBeenCalledWith('لینک آکادمی ویدئویی کپی شد.');});
|
||||
});
|
||||
Reference in new issue
Block a user