|
| 1 | +import { |
| 2 | + QueryClient, |
| 3 | + QueryClientProvider, |
| 4 | +} from 'react-query'; |
| 5 | + |
| 6 | +import { renderHook, act } from '@testing-library/react-hooks'; |
| 7 | +import { useOkapiKy } from '@folio/stripes/core'; |
| 8 | + |
| 9 | +import { useDebouncedQuery } from './useDebouncedQuery'; |
| 10 | + |
| 11 | +const DELAY = 300; |
| 12 | +const mockData = { poLines: [{ id: 'poLine-1', poLineNumber: '11111' }] }; |
| 13 | + |
| 14 | +jest.useFakeTimers('modern'); |
| 15 | +const mockDataFormatter = jest.fn(({ poLines }) => { |
| 16 | + return poLines.map(({ id, poLineNumber }) => ({ label: poLineNumber, value: id })); |
| 17 | +}); |
| 18 | + |
| 19 | +const queryClient = new QueryClient(); |
| 20 | +const wrapper = ({ children }) => ( |
| 21 | + <QueryClientProvider client={queryClient}> |
| 22 | + {children} |
| 23 | + </QueryClientProvider> |
| 24 | +); |
| 25 | + |
| 26 | +describe('useDebouncedQuery', () => { |
| 27 | + beforeEach(() => { |
| 28 | + jest.clearAllMocks(); |
| 29 | + useOkapiKy.mockReturnValue({ |
| 30 | + get: jest.fn(() => ({ |
| 31 | + json: () => Promise.resolve(mockData), |
| 32 | + })), |
| 33 | + }); |
| 34 | + }); |
| 35 | + |
| 36 | + it('should not call `dataFormatter` and return empty []', async () => { |
| 37 | + const { result } = renderHook(() => useDebouncedQuery({ |
| 38 | + api: 'api', |
| 39 | + queryBuilder: jest.fn(), |
| 40 | + dataFormatter: mockDataFormatter, |
| 41 | + debounceDelay: DELAY, |
| 42 | + }), { wrapper }); |
| 43 | + |
| 44 | + await act(async () => { |
| 45 | + await result.current.setSearchQuery(''); |
| 46 | + jest.advanceTimersByTime(1500); |
| 47 | + }); |
| 48 | + |
| 49 | + expect(mockDataFormatter).toHaveBeenCalledTimes(0); |
| 50 | + expect(result.current.options).toEqual([]); |
| 51 | + }); |
| 52 | + |
| 53 | + it('should call `dataFormatter` and return options', async () => { |
| 54 | + const { result } = renderHook(() => useDebouncedQuery({ |
| 55 | + api: 'api', |
| 56 | + queryBuilder: jest.fn(), |
| 57 | + dataFormatter: mockDataFormatter, |
| 58 | + }), { wrapper }); |
| 59 | + |
| 60 | + await act(async () => { |
| 61 | + await result.current.setSearchQuery('test'); |
| 62 | + jest.advanceTimersByTime(1500); |
| 63 | + }); |
| 64 | + |
| 65 | + expect(mockDataFormatter).toHaveBeenCalledTimes(1); |
| 66 | + expect(result.current.options).toEqual([{ label: '11111', value: 'poLine-1' }]); |
| 67 | + }); |
| 68 | + |
| 69 | + it('should call default `dataFormatter` when `dataFormatter` is not present', async () => { |
| 70 | + const { result } = renderHook(() => useDebouncedQuery({ |
| 71 | + api: 'api', |
| 72 | + queryBuilder: jest.fn(), |
| 73 | + }), { wrapper }); |
| 74 | + |
| 75 | + await act(async () => { |
| 76 | + await result.current.setSearchQuery('test'); |
| 77 | + jest.advanceTimersByTime(1500); |
| 78 | + }); |
| 79 | + |
| 80 | + expect(result.current.options).toEqual(mockData); |
| 81 | + }); |
| 82 | +}); |
0 commit comments