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) =>
{children}
, }, })); // Mock next/image vi.mock('next/image', () => ({ default: ({ src, alt, className }: any) => {alt}, })); // Mock next/link vi.mock('next/link', () => ({ default: ({ children, href, className, ...props }: any) => ( {children} ), })); // 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 empty state without static fallback 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(); // 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(); // Verify empty state is rendered (no static fallback data shown) 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(); 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(); 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(); 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(); await waitFor(() => { 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(); 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(); 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(); 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(); 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(); 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(); 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(); 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(); await waitFor(() => expect(screen.getByText('آب گوشت گاو')).toBeInTheDocument()); expect(screen.getByTestId('wiki-ingredient-code')).toHaveClass('max-w-full', 'break-all'); }); });