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> = {}; 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) => })); 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();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();await screen.findByText('Joint Alpha');view.rerender();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();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();await screen.findByText('Joint Alpha');expect(screen.getByText('توصیه شده برای Rex')).toBeInTheDocument();expect(screen.getByText('مخصوص گربه')).toBeInTheDocument();expect(screen.getAllByText('مناسب برای Rex')).toHaveLength(2);}); });