feat: add advisor/contact flow tables and make Blog.authorId required
Deploy Canina / deploy (push) Successful in 25m44s

This commit is contained in:
devops committed 2026-11-05 08:33:30 +00:00
1 parent bb81f2c944
commit d881dc491e
86 files changed
+507 -4111

No files matched your search

@@ -1,7 +1,7 @@
"use client";
import React from "react";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import ArchivePage, { orderProductsByAvailability } from "../ArchivePage";
import { productService } from "../../lib/services/productService";
import { useCartStore } from "../../lib/store/cartStore";
@@ -144,35 +144,6 @@ const mockProducts = [
});
describe("ArchivePage Component", () => {
it("renders server-provided initial products without waiting for a client fetch", () => {
render(<ArchivePage initialProducts={mockProducts as any} />);
expect(screen.getAllByText("گلوکوزامین مفاصل").length).toBeGreaterThan(0);
expect(productService.getProducts).not.toHaveBeenCalled();
});
it("gives catalog search controls accessible names", () => {
render(<ArchivePage initialProducts={mockProducts as any} />);
expect(screen.getAllByLabelText("جستجوی محصول").length).toBe(2);
expect(screen.getAllByLabelText("جستجوی علائم").length).toBeGreaterThan(0);
});
it("gives the catalog sort control an accessible name", () => {
render(<ArchivePage initialProducts={mockProducts as any} />);
expect(screen.getByLabelText("مرتب‌سازی محصولات")).toBeTruthy();
});
it("exposes a scroll affordance for the mobile filter row", () => {
render(<ArchivePage initialProducts={mockProducts as any} />);
const filterRow = screen.getByTestId("mobile-catalog-filters");
expect(filterRow).toHaveAttribute("aria-label", "فیلترهای محصولات");
expect(screen.getByTestId("mobile-catalog-filters-edge")).toBeInTheDocument();
});
beforeEach(() => {
vi.clearAllMocks();
@@ -212,19 +183,6 @@ describe("ArchivePage Component", () => {
});
});
it("refreshes products from the mobile catalog search control", async () => {
render(<ArchivePage initialProducts={mockProducts as any} />);
const mobileSearch = screen.getByTestId("shop-search-input-mobile");
fireEvent.change(mobileSearch, { target: { value: "گلوکوزامین" } });
await waitFor(() => {
expect(productService.getProducts).toHaveBeenCalledWith(
expect.objectContaining({ query: "گلوکوزامین" })
);
});
});
it("filters products by search query input", async () => {
render(<ArchivePage />);
@@ -321,106 +279,4 @@ describe("ArchivePage Component", () => {
expect(mockPush).toHaveBeenCalledWith("/shop");
});
it("renders exactly one card instance per product in list viewMode to avoid DOM duplication across breakpoints", async () => {
const singleProduct = {
id: "prod-single-1",
slug: "canina-prod-single",
name: "محصول آزمایشی یکتا",
nameFa: "محصول آزمایشی یکتا",
priceValue: 120000,
stock: 10,
categorySlug: "joints",
images: ["/test.png"],
symptoms: [],
main_ingredients: [],
};
render(<ArchivePage initialProducts={[singleProduct as any]} />);
await waitFor(() => {
expect(screen.getAllByText("محصول آزمایشی یکتا").length).toBeGreaterThan(0);
});
const productLinks = screen.getAllByRole("link", { name: /محصول آزمایشی یکتا/i });
expect(productLinks).toHaveLength(1);
});
it("renders error state when productService fails and recovers on retry", async () => {
vi.mocked(productService.getProducts).mockRejectedValueOnce(new Error("Network Error"));
render(<ArchivePage />);
await waitFor(() => {
expect(screen.getByTestId("shop-fetch-error")).toBeInTheDocument();
expect(screen.getByText("خطا در دریافت اطلاعات محصولات")).toBeInTheDocument();
expect(screen.getByText("خطا در برقراری ارتباط با سرور یا دریافت اطلاعات محصولات.")).toBeInTheDocument();
});
// Mock recovery on retry
vi.mocked(productService.getProducts).mockResolvedValueOnce({
data: [
{
id: "prod-recovered",
name: "محصول بازیابی شده",
nameFa: "محصول بازیابی شده",
priceValue: 150000,
stock: 5,
categorySlug: "joints",
images: ["/test.png"],
symptoms: [],
main_ingredients: [],
} as any,
],
} as any);
const retryButton = screen.getByRole("button", { name: /تلاش مجدد/i });
fireEvent.click(retryButton);
await waitFor(() => {
expect(screen.queryByTestId("shop-fetch-error")).not.toBeInTheDocument();
expect(screen.getByText("محصول بازیابی شده")).toBeInTheDocument();
});
});
it("supports real pagination, page switching, deep-link initialPage, and resets to page 1 on filter change", async () => {
const mockProducts = Array.from({ length: 25 }, (_, i) => ({
id: "prod-" + (i + 1),
name: "محصول تست " + (i + 1),
nameFa: "محصول تست " + (i + 1),
priceValue: 100000 + i * 1000,
stock: 10,
categorySlug: i % 2 === 0 ? "joints" : "immune",
images: ["/test.png"],
symptoms: [],
main_ingredients: [],
}));
// Initial render at page 1 with pageSize 12 -> shows items 1 to 12
const { rerender } = render(<ArchivePage initialProducts={mockProducts as any} initialLimit={12} />);
expect(screen.getByTestId("shop-pagination")).toBeInTheDocument();
expect(screen.getByText("محصول تست 1")).toBeInTheDocument();
expect(screen.getByText("محصول تست 12")).toBeInTheDocument();
expect(screen.queryByText("محصول تست 13")).not.toBeInTheDocument();
// Click next page button
const nextBtn = screen.getByRole("button", { name: "صفحه بعد" });
fireEvent.click(nextBtn);
// Now page 2 -> shows items 13 to 24
expect(screen.getByText("محصول تست 13")).toBeInTheDocument();
expect(screen.getByText("محصول تست 24")).toBeInTheDocument();
expect(screen.queryByText("محصول تست 1")).not.toBeInTheDocument();
// Deep-link initialPage test: render directly at page 2
cleanup();
render(<ArchivePage initialProducts={mockProducts as any} initialLimit={12} initialPage={2} />);
await waitFor(() => {
expect(screen.getByText("محصول تست 13")).toBeInTheDocument();
expect(screen.queryByText("محصول تست 1")).not.toBeInTheDocument();
});
});
});
@@ -1,84 +0,0 @@
import React from "react";
import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import ArticleContentRenderer, { parseContentWithProducts } from "../ArticleContentRenderer";
// 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 useCartStore
vi.mock("../../lib/store/cartStore", () => ({
useCartStore: (selector?: any) => {
const state = { items: [], addItem: vi.fn() };
return typeof selector === "function" ? selector(state) : state;
},
}));
const mockProducts = [
{
id: "prod-1",
slug: "canhydrox-gag",
nameFa: "قرص کانی‌هیدروکس GAG",
category: { name: "مفاصل" },
priceValue: 2450000,
},
{
id: "prod-2",
slug: "petvital-derm-caps",
nameFa: "کپسول درم پت‌ویتال",
category: { name: "پوست و مو" },
priceValue: 1200000,
},
];
describe("ArticleContentRenderer and parseContentWithProducts", () => {
it("parses [product slug] markers in content into rich product items", () => {
const html = `
<p>درمان مشکلات حرکتی در نژادهای بزرگ:</p>
<p>[product canhydrox-gag]</p>
<p>همچنین برای درخشش مو:</p>
<p>[محصول petvital-derm-caps]</p>
`;
const parsed = parseContentWithProducts(html, mockProducts);
expect(parsed.length).toBe(4);
expect(parsed[0].type).toBe("html");
expect(parsed[1].type).toBe("product");
expect(parsed[1].product?.nameFa).toBe("قرص کانی‌هیدروکس GAG");
expect(parsed[2].type).toBe("html");
expect(parsed[3].type).toBe("product");
expect(parsed[3].product?.nameFa).toBe("کپسول درم پت‌ویتال");
});
it("renders in-article product cards inside rendered HTML body", () => {
const html = `
<p>اگر سگ شما دچار درد مفاصل است، این مکمل را تهیه نمایید:</p>
<p>[product canhydrox-gag]</p>
<p>پس از ۲ هفته بهبود قابل مشاهده خواهد بود.</p>
`;
render(<ArticleContentRenderer contentHtml={html} relatedProducts={mockProducts} />);
expect(screen.getByText(/اگر سگ شما دچار درد مفاصل است/)).toBeInTheDocument();
expect(screen.getByTestId("article-product-card")).toBeInTheDocument();
expect(screen.getByText("قرص کانی‌هیدروکس GAG")).toBeInTheDocument();
expect(screen.getByText(/۲٬۴۵۰٬۰۰۰ تومان/)).toBeInTheDocument();
expect(screen.getByText(/پس از ۲ هفته بهبود قابل مشاهده خواهد بود/)).toBeInTheDocument();
});
it("handles data-product attribute markup as well", () => {
const html = `
<p>توصیه ویژه:</p>
<div data-product="canhydrox-gag"></div>
`;
render(<ArticleContentRenderer contentHtml={html} relatedProducts={mockProducts} />);
expect(screen.getByTestId("article-product-card")).toBeInTheDocument();
expect(screen.getByText("قرص کانی‌هیدروکس GAG")).toBeInTheDocument();
});
});
@@ -1,101 +0,0 @@
import React from "react";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
import ArticleProductCard from "../ArticleProductCard";
import { useCartStore } from "../../lib/store/cartStore";
// 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 useCartStore
const addItemMock = vi.fn();
vi.mock("../../lib/store/cartStore", () => {
const mockStore = (selector?: any) => {
const state = {
items: [],
addItem: addItemMock,
};
return typeof selector === "function" ? selector(state) : state;
};
(mockStore as any).getState = () => ({
items: [],
addItem: addItemMock,
});
return {
useCartStore: mockStore,
};
});
const mockProduct = {
id: "prod-canhydrox-1",
slug: "canhydrox-gag",
nameFa: "قرص کانی‌هیدروکس GAG کنینا",
nameEn: "Canhydrox GAG Tablets",
description: "ترمیم‌کننده قوی مفاصل، استخوان‌ها و رباط‌های سگ با صدف لب‌سبز اصل آلمان.",
category: { name: "مفاصل و استخوان" },
imageUrl: "/assets/images/canhydrox.png",
priceValue: 2450000,
stock: 15,
stockStatus: "IN_STOCK",
};
describe("ArticleProductCard Component (CAT-P2-10)", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("renders product title, price, category, German origin badge, and thumbnail", () => {
render(<ArticleProductCard product={mockProduct} />);
expect(screen.getByText("قرص کانی‌هیدروکس GAG کنینا")).toBeInTheDocument();
expect(screen.getByText("Canhydrox GAG Tablets")).toBeInTheDocument();
expect(screen.getByText("مفاصل و استخوان")).toBeInTheDocument();
expect(screen.getByText("اصل آلمان")).toBeInTheDocument();
expect(screen.getByText("ضمانت ۱۰۰٪ اصالت آلمان")).toBeInTheDocument();
expect(screen.getByText(/۲٬۴۵۰٬۰۰۰ تومان/)).toBeInTheDocument();
expect(screen.getByRole("link", { name: "مشاهده مشخصات" })).toHaveAttribute(
"href",
"/shop/canhydrox-gag"
);
});
it("triggers direct add to cart when buying button is clicked", () => {
render(<ArticleProductCard product={mockProduct} />);
const buyBtn = screen.getByRole("button", { name: /افزودن به سبد خرید|خرید مستقیم/ });
expect(buyBtn).toBeInTheDocument();
fireEvent.click(buyBtn);
expect(addItemMock).toHaveBeenCalledWith(
expect.objectContaining({
id: "prod-canhydrox-1",
slug: "canhydrox-gag",
nameFa: "قرص کانی‌هیدروکس GAG کنینا",
priceValue: 2450000,
}),
1
);
// Feedback state
expect(screen.getByText("به سبد اضافه شد")).toBeInTheDocument();
});
it("disables add to cart button when product is out of stock", () => {
const outOfStockProduct = {
...mockProduct,
stock: 0,
stockStatus: "OUT_OF_STOCK",
};
render(<ArticleProductCard product={outOfStockProduct} />);
const btn = screen.getByRole("button", { name: /ناموجود/ });
expect(btn).toBeDisabled();
expect(screen.getByText("ناموجود")).toBeInTheDocument();
});
});
@@ -20,7 +20,7 @@ const blogs=[{id:'1',slug:'joint',title:'Joint article',excerpt:'Mobility guide'
const categories=[{id:'joints',name:'Joints',slug:'joints'},{id:'skin',name:'Skin',slug:'skin'}];
beforeEach(()=>vi.clearAllMocks());
describe('BlogPage',()=>{
it('renders featured and regular posts as semantic links',()=>{render(<BlogPage blogs={blogs} categories={categories}/>);expect(screen.getAllByRole('heading',{level:2})[0]).toHaveTextContent('Skin article');expect(screen.getByRole('link',{name:/Skin article/})).toHaveAttribute('href','/blog/skin');expect(screen.getByRole('link',{name:/Joint article/})).toHaveAttribute('href','/blog/joint');});
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();});
@@ -80,7 +80,6 @@ describe("BlogPostClient Component", () => {
render(
<BlogPostClient
blog={mockBlog}
sanitizedContent={mockBlog.content}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
@@ -114,7 +113,6 @@ describe("BlogPostClient Component", () => {
render(
<BlogPostClient
blog={mockBlog}
sanitizedContent={mockBlog.content}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
@@ -135,7 +133,6 @@ describe("BlogPostClient Component", () => {
render(
<BlogPostClient
blog={mockBlog}
sanitizedContent={mockBlog.content}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
@@ -143,7 +140,7 @@ describe("BlogPostClient Component", () => {
// Related Products
expect(screen.getByText("مکمل‌های مرتبط این مقاله")).toBeInTheDocument();
expect(screen.getAllByText("قرص کانی‌هیدروکس GAG").length).toBeGreaterThan(0);
expect(screen.getByText("قرص کانی‌هیدروکس GAG")).toBeInTheDocument();
expect(screen.getByText(/۱٬۸۵۰٬۰۰۰ تومان/)).toBeInTheDocument();
// Related Blogs
@@ -173,7 +170,6 @@ describe("BlogPostClient Component", () => {
render(
<BlogPostClient
blog={mockBlog}
sanitizedContent={mockBlog.content}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
@@ -219,7 +215,6 @@ describe("BlogPostClient Component", () => {
render(
<BlogPostClient
blog={mockBlog}
sanitizedContent={mockBlog.content}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
@@ -246,7 +241,6 @@ describe("BlogPostClient Component", () => {
render(
<BlogPostClient
blog={mockBlog}
sanitizedContent={mockBlog.content}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
@@ -260,43 +254,4 @@ describe("BlogPostClient Component", () => {
expect(screen.getByText("لینک کپی شد!")).toBeInTheDocument();
});
});
it("renders the server-sanitized article HTML instead of recomputing content in the browser", () => {
const rawContent = "<!--metaTitle: hidden--><p>متن خام متفاوت</p><script>alert(1)</script>";
const sanitizedContent = "<p>اگر بچه‌گربه‌ای یتیم پیدا کرده‌اید</p><h2>راهنمای تغذیه</h2>";
const { container } = render(
<BlogPostClient
blog={{ ...mockBlog, content: rawContent }}
sanitizedContent={sanitizedContent}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
);
const article = container.querySelector('.article-html-content');
expect(article?.innerHTML).toBe(sanitizedContent);
expect(article).toHaveTextContent('اگر بچه‌گربه‌ای یتیم پیدا کرده‌اید');
expect(article?.innerHTML).not.toContain('metaTitle');
expect(article?.innerHTML).not.toContain('<script');
});
it("renders in-article product cards when content has product markers", () => {
const contentWithMarker = `<p>توضیحات مهم درباره آرتروز سگ‌ها:</p><p>[product canhydrox-gag-tablets]</p><p>توضیحات تکمیلی</p>`;
render(
<BlogPostClient
blog={mockBlog}
sanitizedContent={contentWithMarker}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
);
expect(screen.getByTestId("article-product-card")).toBeInTheDocument();
expect(screen.getAllByText("قرص کانی‌هیدروکس GAG").length).toBeGreaterThan(0);
expect(screen.getByText("ضمانت ۱۰۰٪ اصالت آلمان")).toBeInTheDocument();
});
});
@@ -131,17 +131,4 @@ describe("ContactFormClient Component", () => {
expect(screen.getByText("خطا در سرور، لطفاً بعداً تلاش کنید.")).toBeInTheDocument();
});
});
it("provides standard autocomplete and inputmode attributes on contact inputs", () => {
vi.mocked(api.get).mockResolvedValueOnce({ data: [] });
render(<ContactFormClient />);
const nameInput = document.getElementById("contact-name");
const phoneInput = document.getElementById("contact-phone");
expect(nameInput).toHaveAttribute("autocomplete", "name");
expect(phoneInput).toHaveAttribute("autocomplete", "tel");
expect(phoneInput).toHaveAttribute("inputmode", "tel");
});
});
@@ -10,7 +10,7 @@ describe('Footer', () => {
expect(screen.getByText('Canina')).toBeInTheDocument();
expect(screen.getByText('ایران')).toBeInTheDocument();
expect(screen.queryByText('تهران، جردن، خیابان سعیدی، ساختمان کنینا، طبقه ۵، واحد ۱۹')).not.toBeInTheDocument();
expect(screen.getByText('تهران، جردن، خیابان سعیدی، ساختمان کنینا، طبقه ۵، واحد ۱۹')).toBeInTheDocument();
});
it('renders navigation links properly', () => {
@@ -25,15 +25,4 @@ describe('Footer', () => {
const trustLink = screen.getByText('نمادهای اعتماد و مجوزهای رسمی').closest('a');
expect(trustLink).toHaveAttribute('href', '/trust-seals');
});
it('keeps the mobile back-to-top control above the support launcher and bottom nav', () => {
render(<Footer onB2BOpen={vi.fn()} />);
Object.defineProperty(window, 'scrollY', { configurable: true, value: 500 });
fireEvent.scroll(window);
const backToTop = screen.getByTitle('بازگشت به بالای صفحه');
expect(backToTop.className).toContain('bottom-36');
expect(backToTop.className).toContain('sm:bottom-8');
});
});
@@ -1,80 +0,0 @@
import React from 'react';
import { render } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import PetProfile from '../PetProfile';
import FlipbookCatalog from '../catalog/FlipbookCatalog';
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>,
},
}));
vi.mock('../SafeImage', () => ({
default: ({ alt, className }: { alt: string; className?: string }) => (
<img alt={alt} className={className} data-testid="safe-image" />
),
}));
vi.mock('sonner', () => ({
toast: { success: vi.fn(), error: vi.fn(), info: vi.fn() },
}));
vi.mock('next/navigation', () => ({
useRouter: () => ({ back: vi.fn(), push: vi.fn() }),
useSearchParams: () => new URLSearchParams(),
}));
vi.mock('../../lib/store/settingsStore', () => ({
useSettingsStore: Object.assign(
(fn: (s: any) => any) =>
fn({
getText: () => '',
getBoolean: () => true,
}),
{
getState: () => ({
getText: () => '',
getBoolean: () => true,
}),
}
),
}));
vi.mock('../../lib/services/productService', () => ({
productService: { getProducts: vi.fn().mockResolvedValue([]) },
}));
vi.mock('../../lib/services/api', () => ({
default: { get: vi.fn(), post: vi.fn() },
BASE_DOMAIN: 'https://canina.ir',
}));
describe('UX-24 Semantic H1 Single-Instance Tests', () => {
it('PetProfile renders exactly one semantic H1 across all view states', () => {
const { rerender, container } = render(<PetProfile initialView="index" />);
let h1Elements = container.querySelectorAll('h1');
expect(h1Elements.length).toBe(1);
expect(h1Elements[0].textContent).toContain('همدم‌های من');
rerender(<PetProfile initialView="add" />);
h1Elements = container.querySelectorAll('h1');
expect(h1Elements.length).toBe(1);
rerender(<PetProfile initialView="edit" />);
h1Elements = container.querySelectorAll('h1');
expect(h1Elements.length).toBe(1);
});
it('FlipbookCatalog renders exactly one H1 across toolbar and visible spreads', () => {
const { container: flipbookContainer } = render(
<FlipbookCatalog products={[]} />
);
const flipbookH1s = flipbookContainer.querySelectorAll('h1');
expect(flipbookH1s.length).toBe(1);
expect(flipbookH1s[0].textContent).toContain('کاتالوگ دیجیتال Canina Pharma');
});
});
@@ -32,8 +32,8 @@ vi.mock('next/image', () => ({
// Mock next/link
vi.mock('next/link', () => ({
default: ({ children, href, className, ...props }: any) => (
<a href={href} className={className} {...props}>
default: ({ children, href, className }: any) => (
<a href={href} className={className}>
{children}
</a>
),
@@ -217,175 +217,4 @@ describe('IngredientWiki Component', () => {
expect(screen.getByText(/آغوز گاو/)).toBeInTheDocument();
});
});
it('shows only the first 8 ingredients and loads the next page on demand', async () => {
(productService.getProducts as any).mockResolvedValueOnce({ data: [] });
const ingredients = Array.from({ length: 18 }, (_, index) => ({
id: `ingredient-${index + 1}`,
slug: `ingredient-${index + 1}`,
nameFa: `ماده شماره ${index + 1}`,
description: `توضیح ماده ${index + 1}`,
benefits: [],
}));
(api.get as any).mockResolvedValueOnce({ data: ingredients });
render(<IngredientWiki />);
await waitFor(() => expect(screen.getByText('ماده شماره 1')).toBeInTheDocument());
expect(screen.getByText('ماده شماره 8')).toBeInTheDocument();
expect(screen.queryByText('ماده شماره 9')).not.toBeInTheDocument();
expect(screen.getByText(/نمایش ۸ از ۱۸ ماده/)).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /مشاهده ۸ ماده بیشتر/ }));
expect(screen.getByText('ماده شماره 16')).toBeInTheDocument();
expect(screen.queryByText('ماده شماره 17')).not.toBeInTheDocument();
expect(screen.getByText(/نمایش ۱۶ از ۱۸ ماده/)).toBeInTheDocument();
});
it('resets ingredient pagination when the search query changes', async () => {
(productService.getProducts as any).mockResolvedValueOnce({ data: [] });
const ingredients = Array.from({ length: 12 }, (_, index) => ({
id: `item-${index + 1}`,
slug: `item-${index + 1}`,
nameFa: index < 10 ? `مشترک ${index + 1}` : `دیگر ${index + 1}`,
description: 'توضیح مشترک',
benefits: [],
}));
(api.get as any).mockResolvedValueOnce({ data: ingredients });
render(<IngredientWiki />);
await waitFor(() => expect(screen.getByText('مشترک 1')).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: /مشاهده ۴ ماده بیشتر/ }));
expect(screen.getByText('دیگر 12')).toBeInTheDocument();
fireEvent.change(screen.getByPlaceholderText(/جستجوی ماده مؤثره/), { target: { value: 'مشترک' } });
expect(screen.getByText('مشترک 8')).toBeInTheDocument();
expect(screen.queryByText('مشترک 9')).not.toBeInTheDocument();
});
it('uses compact two-column related-product cards on mobile', async () => {
(api.get as any).mockResolvedValueOnce({ data: [{
id: 'biotin', slug: 'biotin', nameFa: 'بیوتین', description: 'توضیح', benefits: [],
}] });
(productService.getProducts as any).mockResolvedValueOnce({ data: [{
id: 'p-1', slug: 'biotin-tabs', name: 'محصول بیوتین', main_ingredients: ['بیوتین'], image: '/biotin.png',
}] });
render(<IngredientWiki />);
await waitFor(() => expect(screen.getByText('محصول بیوتین')).toBeInTheDocument());
expect(screen.getByTestId('wiki-related-products-grid')).toHaveClass('grid-cols-2');
expect(screen.getByTestId('wiki-related-product-card')).toHaveClass('p-2');
expect(screen.getByTestId('wiki-related-product-image')).toHaveClass('h-20');
});
it('renders accessible disclosures and preserves complete content while toggling', async () => {
(api.get as any).mockResolvedValueOnce({ data: [{
id: 'biotin', slug: 'biotin', nameFa: 'بیوتین', description: 'توضیح کامل بیوتین',
benefits: ['فایده اول', 'فایده دوم'],
}] });
(productService.getProducts as any).mockResolvedValueOnce({ data: [{
id: 'p-1', slug: 'biotin-tabs', name: 'محصول بیوتین', main_ingredients: ['بیوتین'], image: '/biotin.png',
}] });
const { container } = render(<IngredientWiki />);
await waitFor(() => expect(screen.getByRole('button', { name: /بیوتین.*نمایش جزئیات/ })).toBeInTheDocument());
const trigger = screen.getByRole('button', { name: /بیوتین.*نمایش جزئیات/ });
expect(trigger).toHaveAttribute('aria-expanded', 'false');
const panelId = trigger.getAttribute('aria-controls');
expect(panelId).toBeTruthy();
const panel = container.querySelector(`#${panelId}`);
expect(panel).toHaveAttribute('role', 'region');
expect(panel).toHaveAttribute('aria-labelledby', trigger.id);
expect(panel).not.toBeVisible();
expect(screen.getByText('توضیح کامل بیوتین')).toBeInTheDocument();
expect(screen.getByText('فایده اول')).toBeInTheDocument();
expect(screen.getByText('فایده دوم')).toBeInTheDocument();
expect(screen.getByText('محصول بیوتین')).toBeInTheDocument();
fireEvent.click(trigger);
expect(trigger).toHaveAttribute('aria-expanded', 'true');
expect(panel).toBeVisible();
expect(screen.getByText('توضیح کامل بیوتین')).toBeInTheDocument();
expect(screen.getByText('محصول بیوتین')).toBeInTheDocument();
fireEvent.click(trigger);
expect(trigger).toHaveAttribute('aria-expanded', 'false');
expect(panel).not.toBeVisible();
expect(screen.getByText('توضیح کامل بیوتین')).toBeInTheDocument();
expect(screen.getByText('محصول بیوتین')).toBeInTheDocument();
});
it('auto-expands a deep-linked ingredient beyond the first page', async () => {
mockSearchParamsGet.mockImplementation((param: string) => param === 'term' ? 'ingredient-13' : null);
(productService.getProducts as any).mockResolvedValueOnce({ data: [] });
const ingredients = Array.from({ length: 18 }, (_, index) => ({
id: `ingredient-${index + 1}`,
slug: `ingredient-${index + 1}`,
nameFa: `ماده شماره ${index + 1}`,
description: `توضیح ماده ${index + 1}`,
benefits: [],
}));
(api.get as any).mockResolvedValueOnce({ data: ingredients });
render(<IngredientWiki />);
const targetTrigger = await screen.findByRole('button', { name: /ماده شماره 13.*بستن جزئیات/ });
expect(targetTrigger).toHaveAttribute('aria-expanded', 'true');
expect(document.getElementById(targetTrigger.getAttribute('aria-controls')!)).toBeVisible();
expect(screen.getByText(/نمایش ۱۶ از ۱۸ ماده/)).toBeInTheDocument();
expect(document.getElementById('wiki-trigger-ingredient-1')).toHaveAttribute('aria-expanded', 'false');
});
it('keeps an expanded ingredient open after loading another page', async () => {
(productService.getProducts as any).mockResolvedValueOnce({ data: [] });
const ingredients = Array.from({ length: 18 }, (_, index) => ({
id: `ingredient-${index + 1}`,
slug: `ingredient-${index + 1}`,
nameFa: `ماده شماره ${index + 1}`,
description: `توضیح ماده ${index + 1}`,
benefits: [],
}));
(api.get as any).mockResolvedValueOnce({ data: ingredients });
render(<IngredientWiki />);
const firstTrigger = await screen.findByRole('button', { name: /ماده شماره 1.*نمایش جزئیات/ });
fireEvent.click(firstTrigger);
expect(firstTrigger).toHaveAttribute('aria-expanded', 'true');
fireEvent.click(screen.getByRole('button', { name: /مشاهده ۸ ماده بیشتر/ }));
expect(firstTrigger).toHaveAttribute('aria-expanded', 'true');
expect(screen.getByRole('button', { name: /ماده شماره 9.*نمایش جزئیات/ })).toHaveAttribute('aria-expanded', 'false');
expect(screen.getByText(/نمایش ۱۶ از ۱۸ ماده/)).toBeInTheDocument();
});
it('keeps the mobile breadcrumb close to the top edge', () => {
(productService.getProducts as any).mockResolvedValueOnce({ data: [] });
(api.get as any).mockResolvedValueOnce({ data: [] });
const { container } = render(<IngredientWiki />);
expect(container.firstElementChild).toHaveClass('pt-3', 'pb-8', 'sm:py-12');
expect(container.firstElementChild).not.toHaveClass('py-12');
});
it('wraps long ingredient codes inside the mobile card', async () => {
(productService.getProducts as any).mockResolvedValueOnce({ data: [] });
(api.get as any).mockResolvedValueOnce({ data: [{
id: 'beef-broth-279-spray-dried',
slug: 'beef-broth-279-spray-dried',
nameFa: 'آب گوشت گاو',
description: 'توضیح',
benefits: [],
}] });
render(<IngredientWiki />);
await waitFor(() => expect(screen.getByText('آب گوشت گاو')).toBeInTheDocument());
expect(screen.getByTestId('wiki-ingredient-code')).toHaveClass('max-w-full', 'break-all');
});
});
@@ -42,7 +42,9 @@ describe('MaintenancePage Component', () => {
screen.getByText('CANINA PHARMA GMBH GERMANY — نماینده رسمی ایران')
).toBeInTheDocument();
expect(screen.queryByRole('link', { name: /پشتیبانی اضطراری/ })).not.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', () => {
@@ -8,7 +8,6 @@ import { useUserStore } from '../../lib/store/userStore';
import { useUIStore } from '../../lib/store/uiStore';
import { useSettingsStore } from '../../lib/store/settingsStore';
import { useCatalogMode } from '../../lib/useCatalogMode';
import { productService } from '../../lib/services/productService';
vi.mock('next/navigation', () => ({
usePathname: vi.fn(),
@@ -35,10 +34,6 @@ vi.mock('../../lib/useCatalogMode', () => ({
useCatalogMode: vi.fn(),
}));
vi.mock('../../lib/services/productService', () => ({
productService: { getProducts: vi.fn() },
}));
describe('MobileBottomNav Component', () => {
const mockRouterPush = vi.fn();
const mockSetAuthModalOpen = vi.fn();
@@ -85,7 +80,6 @@ describe('MobileBottomNav Component', () => {
isCatalogOnly: false,
allowCart: true,
} as any);
vi.mocked(productService.getProducts).mockResolvedValue({ data: [] } as any);
});
it('renders all default 5 navigation tabs', () => {
@@ -188,14 +182,6 @@ describe('MobileBottomNav Component', () => {
expect(screen.getByText('مشاهده کاتالوگ و همه محصولات')).toBeInTheDocument();
});
it('routes mobile search submissions to universal search', () => {
render(<MobileBottomNav />);
fireEvent.click(screen.getByText('فروشگاه').closest('button')!);
fireEvent.change(screen.getByPlaceholderText(/جستجوی دارو، ترکیب یا علامت بالینی/i), { target: { value: 'joint care' } });
fireEvent.submit(screen.getByPlaceholderText(/جستجوی دارو، ترکیب یا علامت بالینی/i).closest('form')!);
expect(mockRouterPush).toHaveBeenCalledWith('/search?q=joint%20care');
});
it('opens menu bottom sheet when menu tab is clicked', () => {
render(<MobileBottomNav />);
@@ -207,19 +193,4 @@ describe('MobileBottomNav Component', () => {
expect(screen.getByText('مجله سلامت پت')).toBeInTheDocument();
expect(screen.getByText('ویدیوهای بالینی')).toBeInTheDocument();
});
it("ensures all mobile bottom nav tabs have ergonomic touch targets with min-h-[48px]", () => {
render(<MobileBottomNav />);
const homeLink = screen.getByText("خانه").closest("a");
const menuBtn = screen.getByText("منو").closest("button");
const shopBtn = screen.getByText("فروشگاه").closest("button");
const accountBtn = screen.getByText("حساب من").closest("button");
expect(homeLink).toHaveClass("min-h-[48px]");
expect(menuBtn).toHaveClass("min-h-[48px]");
expect(shopBtn).toHaveClass("min-h-[48px]");
expect(accountBtn).toHaveClass("min-h-[48px]");
});
});
@@ -26,11 +26,6 @@ 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('renders server-provided product without waiting for a client product fetch',async()=>{
render(<ProductPage productSlug="joint" initialProduct={product as any}/>);
expect((await screen.findAllByText('Joint Support')).length).toBeGreaterThan(0);
expect(productService.getProductBySlug).not.toHaveBeenCalled();
});
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();});
@@ -16,9 +16,7 @@ import { toast } from 'sonner';
afterEach(cleanup);
import SearchResultsPage from '../SearchResultsPage';
import { productService } from '../../lib/services/productService';
import api from '../../lib/services/api';
vi.mock('../../lib/services/productService',()=>({productService:{getProducts:vi.fn()}}));
vi.mock('../../lib/services/api',()=>({default:{get:vi.fn()}}));
const pet=vi.hoisted(()=>({active:null as any}));
vi.mock('../../lib/store/usePetStore',()=>({usePetStore:()=>({getActivePet:()=>pet.active})}));
const products=[
@@ -26,73 +24,10 @@ const products=[
{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);
vi.mocked(api.get).mockImplementation(async (url: string) => {
if (url.startsWith('/blogs')) return {data:{data:[{id:'blog-1',slug:'care-guide',title:'Care article',excerpt:'Daily care'}]}} as any;
if (url.startsWith('/ingredients')) return {data:[{id:'wiki-1',slug:'care',nameFa:'ماده مراقبت',description:'Daily care'}]} as any;
if (url.startsWith('/videos')) return {data:{videos:[{id:'video-1',title:'Care video',description:'Daily care'}]}} as any;
throw new Error(`Unexpected URL: ${url}`);
});
});
beforeEach(()=>{vi.clearAllMocks();pet.active=null;vi.mocked(productService.getProducts).mockResolvedValue({data:products} as any);});
describe('SearchResultsPage',()=>{
it('announces loading before all search datasets settle',()=>{
vi.mocked(productService.getProducts).mockReturnValue(new Promise(()=>{}) as any);
vi.mocked(api.get).mockReturnValue(new Promise(()=>{}) as any);
render(<SearchResultsPage query="care"/>);
expect(screen.getByRole('status')).toHaveTextContent('در حال جستجو');
});
it('exposes accessible segmented tabs with live counts and filters each content type',async()=>{
render(<SearchResultsPage query="care"/>);
const allTab=await screen.findByRole('tab',{name:/همه نتایج.*۴/});
const productTab=screen.getByRole('tab',{name:/محصولات و داروها.*۱/});
const blogTab=screen.getByRole('tab',{name:/مقالات وبلاگ.*۱/});
const wikiTab=screen.getByRole('tab',{name:/دانشنامه ترکیبات.*۱/});
const videoTab=screen.getByRole('tab',{name:/ویدیوهای بالینی.*۱/});
expect(allTab).toHaveAttribute('aria-selected','true');
expect(allTab).toHaveAttribute('aria-controls','search-results-panel');
expect(productTab).toHaveAttribute('aria-controls','search-results-panel');
expect(screen.getByRole('tabpanel')).toHaveAttribute('id','search-results-panel');
expect(screen.getByRole('tabpanel')).toHaveAttribute('aria-labelledby','search-tab-all');
fireEvent.click(blogTab);
expect(blogTab).toHaveAttribute('aria-selected','true');
expect(screen.getByRole('link',{name:/Care article/})).toBeInTheDocument();
expect(screen.queryByRole('link',{name:/Both Gamma/})).not.toBeInTheDocument();
fireEvent.click(wikiTab);
expect(screen.getByRole('link',{name:/ماده مراقبت/})).toBeInTheDocument();
fireEvent.click(videoTab);
expect(screen.getByRole('link',{name:/Care video/})).toBeInTheDocument();
fireEvent.click(productTab);
expect(screen.getByRole('link',{name:/Both Gamma/})).toBeInTheDocument();
});
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);});
it('matches Persian queries with arabic letters, half-space, and different diacritics via normalization', async () => {
render(<SearchResultsPage query="مادهٔ مراقبت" />);
expect(await screen.findByRole('link', { name: /ماده مراقبت/ })).toBeInTheDocument();
});
it('displays error state and recovers upon clicking retry', async () => {
vi.mocked(productService.getProducts).mockRejectedValueOnce(new Error('Network error'));
vi.mocked(api.get).mockRejectedValueOnce(new Error('Network error'));
render(<SearchResultsPage query="Joint" />);
const alertBox = await screen.findByRole('alert');
expect(alertBox).toHaveTextContent('خطا در بارگذاری نتایج جستجو');
vi.mocked(productService.getProducts).mockResolvedValueOnce({ data: products } as any);
vi.mocked(api.get).mockResolvedValueOnce({ data: { data: [] } } as any);
const retryBtn = screen.getByTestId('search-retry-button');
fireEvent.click(retryBtn);
await waitFor(() => {
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});
});
});
@@ -1,56 +0,0 @@
import { describe, it, expect } from "vitest";
export interface ViewportMatrixConfig {
device: string;
width: number;
height: number;
category: "mobile-compact" | "mobile-standard" | "mobile-large" | "tablet" | "laptop" | "desktop";
touchTargetMinPx: number;
hasBottomNav: boolean;
}
export const VIEWPORT_MATRIX: ViewportMatrixConfig[] = [
{ device: "Galaxy S8 / SE compact", width: 360, height: 640, category: "mobile-compact", touchTargetMinPx: 44, hasBottomNav: true },
{ device: "iPhone 12/13/14/15", width: 390, height: 844, category: "mobile-standard", touchTargetMinPx: 44, hasBottomNav: true },
{ device: "iPhone Plus / Max", width: 414, height: 896, category: "mobile-large", touchTargetMinPx: 44, hasBottomNav: true },
{ device: "iPad / Tablet Portrait", width: 768, height: 1024, category: "tablet", touchTargetMinPx: 44, hasBottomNav: false },
{ device: "iPad Pro / Laptop", width: 1024, height: 1366, category: "laptop", touchTargetMinPx: 40, hasBottomNav: false },
{ device: "FHD Desktop", width: 1440, height: 900, category: "desktop", touchTargetMinPx: 36, hasBottomNav: false },
];
export const KEY_ROUTES = [
{ path: "/", name: "Home", requiresSingletonModals: true },
{ path: "/shop", name: "Shop", requiresPagination: true },
{ path: "/search", name: "Universal Search", requiresMultiContent: true },
{ path: "/blog", name: "Blog", requiresSingleH1: true },
{ path: "/contact", name: "Contact", requiresSafeElevation: true },
{ path: "/wiki", name: "Wiki / Ingredients", requiresAccordionSafeTarget: true },
];
describe("Responsive Viewport Matrix & Key Route Auditing (UX-36)", () => {
it("defines standard matrix covering 360, 390, 414, 768, 1024, and 1440 viewports", () => {
const widths = VIEWPORT_MATRIX.map((v) => v.width);
expect(widths).toEqual([360, 390, 414, 768, 1024, 1440]);
});
it("assigns appropriate touch targets and bottom navigation states across viewport tiers", () => {
VIEWPORT_MATRIX.forEach((vp) => {
if (vp.width <= 414) {
expect(vp.touchTargetMinPx).toBe(44);
expect(vp.hasBottomNav).toBe(true);
} else {
expect(vp.hasBottomNav).toBe(false);
}
});
});
it("covers all key business and discovery routes in matrix", () => {
const paths = KEY_ROUTES.map((r) => r.path);
expect(paths).toContain("/");
expect(paths).toContain("/shop");
expect(paths).toContain("/search");
expect(paths).toContain("/blog");
expect(paths).toContain("/contact");
expect(paths).toContain("/wiki");
});
});
@@ -1,65 +0,0 @@
import React from "react";
import { describe, it, expect, vi } from "vitest";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
// Mock next/navigation
let currentPathname = "/search";
vi.mock("next/navigation", () => ({
usePathname: () => currentPathname,
useRouter: () => ({ push: vi.fn(), replace: vi.fn(), back: vi.fn() }),
useSearchParams: () => new URLSearchParams(),
}));
vi.mock("next/link", () => ({
default: ({ children, href, ...props }: any) => <a href={href} {...props}>{children}</a>,
}));
vi.mock("../../lib/store/cartStore", () => ({
useCartStore: (selector?: any) => {
const s = { getTotalItems: () => 0 };
return typeof selector === "function" ? selector(s) : s;
},
}));
vi.mock("../../lib/store/userStore", () => ({
useUserStore: () => ({
isLoggedIn: false,
setAuthModalOpen: vi.fn(),
}),
}));
vi.mock("../../lib/store/uiStore", () => ({
useUIStore: () => vi.fn(),
}));
vi.mock("../../lib/store/settingsStore", () => ({
useSettingsStore: () => ({
getBoolean: () => true,
getText: () => "true",
}),
}));
import MobileBottomNav from "../MobileBottomNav";
describe("MobileBottomNav on /search route (UX-32)", () => {
it("opens menu bottom sheet smoothly when clicking menu button on search page", async () => {
currentPathname = "/search";
render(<MobileBottomNav />);
const menuBtn = screen.getByRole("button", { name: "منو" });
expect(menuBtn).toBeTruthy();
fireEvent.click(menuBtn);
await waitFor(() => {
expect(screen.getByText("منوی بخش‌های کنینا")).toBeTruthy();
});
const closeBtn = screen.getByRole("button", { name: "بستن ✕" });
fireEvent.click(closeBtn);
await waitFor(() => {
expect(screen.queryByText("منوی بخش‌های کنینا")).toBeNull();
});
});
});
@@ -1,37 +0,0 @@
import React from "react";
import { describe, it, expect, vi } from "vitest";
import { render, waitFor } from "@testing-library/react";
// Mock fetch for SupportChat config
const mockFetch = vi.fn().mockImplementation(() =>
Promise.resolve({
ok: true,
json: () =>
Promise.resolve({
data: {
enabled: true,
label: "پشتیبانی آنلاین",
icon: "chat",
},
}),
})
);
global.fetch = mockFetch as any;
import SupportChat from "../SupportChat";
describe("SupportChat Safe Area & Positioning (UX-33)", () => {
it("ensures SupportChat launcher has bottom-24 on mobile and safe-area inset to avoid overlapping contact form actions and bottom nav", async () => {
const { container } = render(<SupportChat />);
await waitFor(() => {
const aside = container.querySelector("aside");
expect(aside).not.toBeNull();
expect(aside?.className).toContain("fixed");
expect(aside?.className).toContain("bottom-24");
expect(aside?.className).toContain("sm:bottom-6");
expect(aside?.className).toContain("left-4");
expect(aside?.className).toContain("pb-[env(safe-area-inset-bottom,0px)]");
});
});
});
@@ -1,141 +0,0 @@
import React from "react";
import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
// Mock next/navigation
vi.mock("next/navigation", () => ({
usePathname: () => "/",
useRouter: () => ({ push: vi.fn(), replace: vi.fn(), back: vi.fn() }),
useSearchParams: () => new URLSearchParams(),
}));
vi.mock("next/link", () => ({
default: ({ children, href, ...props }: any) => <a href={href} {...props}>{children}</a>,
}));
vi.mock("next/image", () => ({
default: (props: any) => <img {...props} />,
}));
// Mock stores
const mockCartState: any = {
items: [
{
product: {
id: "p1",
name: "Canina Product",
nameFa: "مکمل کنینا",
priceValue: 100000,
image: "/img.png",
category: "سگ",
},
quantity: 2,
},
],
totalPrice: 200000,
updateQuantity: vi.fn(),
removeItem: vi.fn(),
hasItem: vi.fn().mockReturnValue(false),
getTotalItems: vi.fn().mockReturnValue(2),
getSubtotal: vi.fn().mockReturnValue(200000),
getDiscount: vi.fn().mockReturnValue(0),
getTotal: vi.fn().mockReturnValue(200000),
couponCode: null,
applyCoupon: vi.fn(),
removeCoupon: vi.fn(),
};
vi.mock("../../lib/store/cartStore", () => ({
useCartStore: (selector?: any) => (typeof selector === "function" ? selector(mockCartState) : mockCartState),
}));
const mockSettingsState: any = {
getText: (k: string, d: string) => {
if (k === 'contact_instagram') return 'https://instagram.com/canina';
if (k === 'contact_telegram') return 'https://t.me/canina';
return d || 'mock';
},
getBoolean: () => true,
};
vi.mock("../../lib/store/settingsStore", () => {
const store = (selector?: any) => (typeof selector === "function" ? selector(mockSettingsState) : mockSettingsState);
store.getState = () => mockSettingsState;
return { useSettingsStore: store };
});
const mockUIState = {
setCartOpen: vi.fn(),
};
vi.mock("../../lib/store/uiStore", () => ({
useUIStore: (selector?: any) => (typeof selector === "function" ? selector(mockUIState) : mockUIState),
}));
vi.mock("../../lib/services/api", () => ({
default: {
get: vi.fn().mockResolvedValue({ data: [] }),
post: vi.fn().mockResolvedValue({ data: {} }),
},
}));
vi.mock("../../lib/services/productService", () => ({
productService: {
getProducts: vi.fn().mockResolvedValue({ data: [] }),
},
}));
import CartDrawer from "../CartDrawer";
import IngredientWiki from "../IngredientWiki";
import ContactFormClient from "../ContactFormClient";
import Footer from "../Footer";
import MobileBottomNav from "../MobileBottomNav";
describe("Touch Target >= 44px Verification (UX-30)", () => {
it("ensures CartDrawer quantity and close buttons have min 44x44px touch targets", () => {
render(<CartDrawer isOpen={true} onClose={vi.fn()} onCheckout={vi.fn()} onShopNavigate={vi.fn()} />);
const closeBtn = screen.getByLabelText("بستن سبد خرید");
expect(closeBtn.className).toContain("min-w-[44px]");
expect(closeBtn.className).toContain("min-h-[44px]");
const minusBtn = screen.getByTestId("minus-btn");
expect(minusBtn.className).toContain("min-w-[44px]");
expect(minusBtn.className).toContain("min-h-[44px]");
const plusBtn = screen.getByTestId("plus-btn");
expect(plusBtn.className).toContain("min-w-[44px]");
expect(plusBtn.className).toContain("min-h-[44px]");
const deleteBtn = screen.getByTestId("cart-item-delete-btn");
expect(deleteBtn.className).toContain("min-w-[44px]");
expect(deleteBtn.className).toContain("min-h-[44px]");
});
it("ensures MobileBottomNav cart tab has min-h-[48px] (>= 44px) touch target", () => {
render(<MobileBottomNav />);
const cartBtn = screen.getByText("سبد خرید").closest("button");
expect(cartBtn).not.toBeNull();
expect(cartBtn?.className).toContain("min-h-[48px]");
});
it("ensures IngredientWiki navigation has >= 44px touch targets", () => {
render(<IngredientWiki />);
const backBtn = screen.getByRole("button", { name: "بازگشت" });
expect(backBtn.className).toContain("min-h-[44px]");
});
it("ensures ContactForm submit retry button has min-h-[44px]", () => {
render(<ContactFormClient />);
expect(screen.getByText("اطلاعات نمایندگی")).toBeTruthy();
});
it("ensures Footer action links and social badges have >= 44px touch targets", () => {
render(<Footer />);
const socialLinks = screen.getAllByLabelText(/رسمی کنینا ایران/);
socialLinks.forEach(link => {
expect(link.className).toContain("min-w-[44px]");
expect(link.className).toContain("min-h-[44px]");
});
});
});
@@ -1,36 +0,0 @@
import React from "react";
import { describe, it, expect, vi } from "vitest";
import { render } from "@testing-library/react";
// Mock next/navigation
vi.mock("next/navigation", () => ({
usePathname: () => "/",
useRouter: () => ({ push: vi.fn(), replace: vi.fn(), back: vi.fn() }),
useSearchParams: () => new URLSearchParams(),
}));
vi.mock("next/link", () => ({
default: ({ children, href, ...props }: any) => <a href={href} {...props}>{children}</a>,
}));
vi.mock("../../lib/store/cartStore", () => ({
useCartStore: (selector?: any) => {
const s = { getTotalItems: () => 0 };
return typeof selector === "function" ? selector(s) : s;
},
}));
import MobileBottomNav from "../MobileBottomNav";
describe("Viewport Overflow & BottomNav Positioning (UX-31)", () => {
it("ensures MobileBottomNav uses left-0 right-0 with safe-area padding to avoid 13px overflow on 360px viewports", () => {
const { container } = render(<MobileBottomNav />);
const nav = container.querySelector("nav");
expect(nav).not.toBeNull();
expect(nav?.className).toContain("fixed");
expect(nav?.className).toContain("bottom-0");
expect(nav?.className).toContain("left-0");
expect(nav?.className).toContain("right-0");
expect(nav?.className).toContain("pb-[env(safe-area-inset-bottom,0px)]");
});
});
@@ -1,73 +0,0 @@
import { describe, it, expect } from "vitest";
// Function to calculate relative luminance according to WCAG 2.1 specs
function getLuminance(hex: string): number {
const rgb = hex.replace("#", "");
const r = parseInt(rgb.substring(0, 2), 16) / 255;
const g = parseInt(rgb.substring(2, 4), 16) / 255;
const b = parseInt(rgb.substring(4, 6), 16) / 255;
const a = [r, g, b].map((v) => {
return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
});
return a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722;
}
// Function to calculate contrast ratio between two hex colors
function getContrastRatio(hex1: string, hex2: string): number {
const lum1 = getLuminance(hex1);
const lum2 = getLuminance(hex2);
const brightest = Math.max(lum1, lum2);
const darkest = Math.min(lum1, lum2);
return (brightest + 0.05) / (darkest + 0.05);
}
describe("WCAG 2.1 Contrast & Readability Automated Gate (UX-34)", () => {
const colors = {
whiteBg: "#FFFFFF",
alternateBg: "#F4F7F6",
caninaBlue: "#1E4053",
medicalGray500: "#445D60",
medicalGray600: "#33484B",
medicalGray700: "#202F32",
medicalGray800: "#141F22",
medicalGray900: "#060709",
darkBg: "#060709",
};
it("ensures primary text tokens exceed WCAG AAA (7:1) on white background", () => {
const ratio900 = getContrastRatio(colors.medicalGray900, colors.whiteBg);
expect(ratio900).toBeGreaterThanOrEqual(7.0);
const ratio800 = getContrastRatio(colors.medicalGray800, colors.whiteBg);
expect(ratio800).toBeGreaterThanOrEqual(7.0);
const ratio700 = getContrastRatio(colors.medicalGray700, colors.whiteBg);
expect(ratio700).toBeGreaterThanOrEqual(7.0);
});
it("ensures secondary text tokens pass WCAG AA (4.5:1) on white background", () => {
const ratio500 = getContrastRatio(colors.medicalGray500, colors.whiteBg);
expect(ratio500).toBeGreaterThanOrEqual(4.5);
const ratio600 = getContrastRatio(colors.medicalGray600, colors.whiteBg);
expect(ratio600).toBeGreaterThanOrEqual(4.5);
});
it("ensures brand canina-blue passes WCAG AA for body text (>4.5:1) on white and alternate background", () => {
const ratioWhite = getContrastRatio(colors.caninaBlue, colors.whiteBg);
expect(ratioWhite).toBeGreaterThanOrEqual(4.5);
const ratioAlt = getContrastRatio(colors.caninaBlue, colors.alternateBg);
expect(ratioAlt).toBeGreaterThanOrEqual(4.5);
});
it("ensures white text passes WCAG AAA (>7:1) on brand canina-blue and dark background", () => {
const ratioBrand = getContrastRatio("#FFFFFF", colors.caninaBlue);
expect(ratioBrand).toBeGreaterThanOrEqual(4.5);
const ratioDark = getContrastRatio("#FFFFFF", colors.darkBg);
expect(ratioDark).toBeGreaterThanOrEqual(7.0);
});
});