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 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();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();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();await screen.findByText('محصول یافت نشد');expect(err).toHaveBeenCalled();err.mockRestore();}); it('adds selected quantity with calculated dosage and respects quantity floor',async()=>{render();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();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();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();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();}); });