Skip to content

Commit

Permalink
test: add test coverages
Browse files Browse the repository at this point in the history
  • Loading branch information
alisher-epam committed Nov 25, 2024
1 parent 7e6a374 commit 3bfb85c
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/hooks/useDebouncedQuery/useDebouncedQuery.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const useDebouncedQuery = ({
const [inputValue, setInputValue] = useState('');
const [options, setOptions] = useState([]);
const ky = useOkapiKy();
const [namespace] = useNamespace({ key: 'locations' });
const [namespace] = useNamespace({ key: 'debounced-query' });

const debouncedSetInputValue = useMemo(() => {
return debounce((value) => setInputValue(value), debounceDelay);
Expand Down
67 changes: 67 additions & 0 deletions lib/hooks/useDebouncedQuery/useDebouncedQuery.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import {
QueryClient,
QueryClientProvider,
} from 'react-query';

import { renderHook, act } from '@testing-library/react-hooks';
import { useOkapiKy } from '@folio/stripes/core';

import { useDebouncedQuery } from './useDebouncedQuery';

const DELAY = 300;

jest.useFakeTimers('modern');
const mockDataFormatter = jest.fn(({ poLines }) => {
return poLines.map(({ id, poLineNumber }) => ({ label: poLineNumber, value: id }));
});

const queryClient = new QueryClient();
const wrapper = ({ children }) => (
<QueryClientProvider client={queryClient}>
{children}
</QueryClientProvider>
);

describe('useDebouncedQuery', () => {
beforeEach(() => {
jest.clearAllMocks();
useOkapiKy.mockReturnValue({
get: jest.fn(() => ({
json: () => Promise.resolve({ poLines: [{ id: 'poLine-1', poLineNumber: '11111' }] }),
})),
});
});

it('should not call `dataFormatter` and return empty []', async () => {
const { result } = renderHook(() => useDebouncedQuery({
api: 'api',
queryBuilder: jest.fn(),
dataFormatter: mockDataFormatter,
debounceDelay: DELAY,
}), { wrapper });

await act(async () => {
await result.current.setInputValue('');
jest.advanceTimersByTime(1500);
});

expect(mockDataFormatter).toHaveBeenCalledTimes(0);
expect(result.current.options).toEqual([]);
});

it('should call `dataFormatter` and return options', async () => {
const { result } = renderHook(() => useDebouncedQuery({
api: 'api',
queryBuilder: jest.fn(),
dataFormatter: mockDataFormatter,
}), { wrapper });

await act(async () => {
await result.current.setInputValue('test');
jest.advanceTimersByTime(1500);
});

expect(mockDataFormatter).toHaveBeenCalledTimes(1);
expect(result.current.options).toEqual([{ label: '11111', value: 'poLine-1' }]);
});
});

0 comments on commit 3bfb85c

Please sign in to comment.