Files
canina/frontend/application/components/__tests__/SearchResultsPage.test.tsx
T
devops 2c3e4bb752
Deploy Canina / deploy (push) Successful in 2m10s
fix(search): connect tabs to results panel
2026-10-17 12:52:00 +00:00

74 lines
6.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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';
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=[
{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);
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}`);
});
});
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);});
});