Вот у меня есть хук, который возвращает две функции. Как мне замокать его и проверить,…
- User
Вот у меня есть хук, который возвращает две функции. Как мне замокать его и проверить, что при определенном условии вызывается одна из функций из хука?
- Assistant
Для замокания хука и проверки вызова определенной функции можно использовать библиотеку
jestв сочетании сreact-testing-library. Вот пример того, как это можно сделать:// Компонент с хуком, возвращающим две функции const useCustomHook = () => { const func1 = () => console.log('Function 1 called'); const func2 = () => console.log('Function 2 called'); return { func1, func2 }; } // Тест для проверки вызова функции func1 при определенном условии test('Function 1 is called when condition is true', () => { let isConditionTrue = true; const mockFunc1 = jest.fn(); const mockFunc2 = jest.fn(); jest.spyOn(React, 'useEffect').mockImplementationOnce((fn) => { fn(); }); jest.spyOn(myModule, 'useCustomHook').mockImplementation(() => { return { func1: mockFunc1, func2: mockFunc2 }; }); render(<MyComponent />); expect(mockFunc1).toHaveBeenCalled(); expect(mockFunc2).not.toHaveBeenCalled(); }); // Тестовый компонент const MyComponent = () => { const { func1, func2 } = useCustomHook(); useEffect(() => { if (isConditionTrue) { func1(); } else { func2(); } }, []); return null; }В данном примере мы замокаем хук
useCustomHookс помощьюjest.spyOn, чтобы возвращать моковые функцииmockFunc1иmockFunc2. Затем мы вызываем компонентMyComponent, который внутри себя вызывает одну из функций в зависимости от значенияisConditionTrue. После этого мы проверяем, что функцияfunc1была вызвана, а функцияfunc2- нет. - User
import { render, screen } from '@testing-library/react'; import { UploadDownloadGraphPanel } from '../UploadDownloadGraphPanel'; import userEvent from '@testing-library/user-event'; import * as hooks from '../../../model/hooks';
jest.mock('../../../model/hooks');
describe('UploadDownloadGraphPanel Component', () => { test('Checking click on upload link call uploadGraph', async () => { const mockUploadGraph = jest.fn();
jest.spyOn(hooks, 'useUploadDownloadGraphPanel').mockReturnValue({ downloadTemplate: jest.fn(), uploadGraph: mockUploadGraph, }); render(<UploadDownloadGraphPanel />); const link = await screen.findByText('загрузить'); await userEvent.click(link); expect(mockUploadGraph).toBeCalled(); });});
Не работает
- Assistant
Чтобы правильно замокать хук
useUploadDownloadGraphPanelв данном тесте, проверьте несколько моментов:- Убедитесь, что импорт хука
useUploadDownloadGraphPanelв файлеUploadDownloadGraphPanelправильный. - Убедитесь, что путь к импорту хука в тесте совпадает с путем в файле
UploadDownloadGraphPanel. - Проверьте, что хук
useUploadDownloadGraphPanelвозвращает правильные функцииdownloadTemplateиuploadGraph.
Если все эти моменты верны, попробуйте изменить способ замокания хука используя
jest.mockвместоjest.spyOn:import { render, screen } from '@testing-library/react'; import { UploadDownloadGraphPanel } from '../UploadDownloadGraphPanel'; import userEvent from '@testing-library/user-event'; import * as hooks from '../../../model/hooks'; jest.mock('../../../model/hooks', () => ({ useUploadDownloadGraphPanel: jest.fn(), })); describe('UploadDownloadGraphPanel Component', () => { test('Checking click on upload link call uploadGraph', async () => { const mockUploadGraph = jest.fn(); hooks.useUploadDownloadGraphPanel.mockReturnValue({ downloadTemplate: jest.fn(), uploadGraph: mockUploadGraph, }); render(<UploadDownloadGraphPanel />); const link = await screen.findByText('загрузить'); await userEvent.click(link); expect(mockUploadGraph).toBeCalled(); }); });Этот код замокает хук
useUploadDownloadGraphPanelс помощьюjest.mockи должен корректно вызывать функциюuploadGraphпри клике на ссылку. - Убедитесь, что импорт хука
- User
import { renderWithForm } from '$ufs-common'; import { THead, Table, Tr } from '@atomic-ui/react'; import { ThSumTitle } from '../ThSumTitle'; import { screen } from '@testing-library/react';
// jest.mock('../../../model', () => ({ // ...jest.requireActual('../../../model/hooks/useGetCurrencyTitle'), // useGetCurrencyTitle: jest.fn().mockReturnValue({ // sumTitle: 'testTitle', // isFetching: false, // error: undefined, // refetch: jest.fn(), // }), // }));
import * as model from '../../../model';
jest.mock('../../../model');
describe('ThSumTitle Component', () => { const spy = jest.spyOn(model, 'useGetCurrencyTitle'); test('Checking render with correct value', async () => { spy.mockImplementationOnce(() => { return { sumTitle: 'testTitle', isFetching: false, error: undefined, refetch: jest.fn() }; }); renderWithForm( , { formProps: { defaultValues: { SUM_FORMAT: 'UNITS', }, }, }, );
expect(await screen.queryByTestId('loadingSumTitle')).not.toBeInTheDocument(); expect(await screen.findByText('Сумма, testTitle')).toBeInTheDocument(); jest.clearAllMocks(); }); test('Checking render loading ', async () => { spy.mockImplementationOnce(() => { return { sumTitle: undefined, isFetching: true, error: undefined, refetch: jest.fn() }; }); renderWithForm( <Table> <THead> <Tr> <ThSumTitle /> </Tr> </THead> </Table>, { formProps: { defaultValues: { SUM_FORMAT: 'UNITS', }, }, }, ); expect(await screen.queryByTestId('loadingSumTitle')).toBeInTheDocument(); });}); второй раз не мокается, скажи почему
- Assistant
Проблема, по которой хук
useGetCurrencyTitleне мокается во втором тесте, скорее всего, связана с тем, чтоjest.mock('../../../model');не осуществляет автоматическое мокание всех экспортированных функций и объектов в модуле, если они не были явно указаны в файле.Для того чтобы мокнуть все экспорты из модуля, можно использовать
* as moduleвместо непосредственного импорта модуля. В вашем случае, можно попробовать следующий подход:import { renderWithForm } from '$ufs-common'; import { THead, Table, Tr } from '@atomic-ui/react'; import { ThSumTitle } from '../ThSumTitle'; import { screen } from '@testing-library/react'; import * as model from '../../../model'; jest.mock('../../../model', () => { const originalModule = jest.requireActual('../../../model'); return { ...originalModule, useGetCurrencyTitle: jest.fn(), }; }); describe('ThSumTitle Component', () => { const spy = jest.spyOn(model, 'useGetCurrencyTitle'); test('Checking render with correct value', async () => { spy.mockImplementationOnce(() => { return { sumTitle: 'testTitle', isFetching: false, error: undefined, refetch: jest.fn() }; }); renderWithForm( <Table> <THead> <Tr> <ThSumTitle /> </Tr> </THead> </Table>, { formProps: { defaultValues: { SUM_FORMAT: 'UNITS', }, }, }, ); expect(await screen.queryByTestId('loadingSumTitle')).not.toBeInTheDocument(); expect(await screen.findByText('Сумма, testTitle')).toBeInTheDocument(); }); test('Checking render loading', async () => { spy.mockImplementationOnce(() => { return { sumTitle: undefined, isFetching: true, error: undefined, refetch: jest.fn() }; }); renderWithForm( <Table> <THead> <Tr> <ThSumTitle /> </Tr> </THead> </Table>, { formProps: { defaultValues: { SUM_FORMAT: 'UNITS', }, }, }, ); expect(await screen.queryByTestId('loadingSumTitle')).toBeInTheDocument(); }); });Этот подход должен гарантировать мокание всех экспортов из модуля
../../../model, включая функциюuseGetCurrencyTitle, что позволит корректно провести тестирование второго теста. - User
TypeError: Cannot destructure property 'sumTitle' of '(0 , _model.useGetCurrencyTitle)(...)' as it is undefined. не работает, ошибка
- Assistant
Ошибка, которую вы получили, свидетельствует о том, что при деструктурировании свойства
sumTitleобъекта, возвращаемого хукомuseGetCurrencyTitle, оно оказалосьundefined. Это может произойти в случае, если вы не правильно установили возвращаемые значения при mock-реализации хука.Попробуйте установить правильные значения
sumTitle,isFetchingи другие значения с помощьюjest.fn()в функции mock-реализации хука.Вот пример того, как это можно сделать:
import { renderWithForm } from '$ufs-common'; import { THead, Table, Tr } from '@atomic-ui/react'; import { ThSumTitle } from '../ThSumTitle'; import { screen } from '@testing-library/react'; import * as model from '../../../model'; jest.mock('../../../model', () => { const originalModule = jest.requireActual('../../../model'); return { ...originalModule, useGetCurrencyTitle: jest.fn().mockReturnValue({ sumTitle: 'testTitle', isFetching: false, error: undefined, refetch: jest.fn(), }), }; }); describe('ThSumTitle Component', () => { test('Checking render with correct value', async () => { renderWithForm( <Table> <THead> <Tr> <ThSumTitle /> </Tr> </THead> </Table>, { formProps: { defaultValues: { SUM_FORMAT: 'UNITS', }, }, }, ); expect(await screen.queryByTestId('loadingSumTitle')).not.toBeInTheDocument(); expect(await screen.findByText('Сумма, testTitle')).toBeInTheDocument(); }); test('Checking render loading', async () => { model.useGetCurrencyTitle.mockReturnValue({ sumTitle: undefined, isFetching: true, error: undefined, refetch: jest.fn(), }); renderWithForm( <Table> <THead> <Tr> <ThSumTitle /> </Tr> </THead> </Table>, { formProps: { defaultValues: { SUM_FORMAT: 'UNITS', }, }, }, ); expect(await screen.queryByTestId('loadingSumTitle')).toBeInTheDocument(); }); });Попробуйте использовать подобный подход, чтобы убедиться, что возвращаемые значения хука
useGetCurrencyTitleправильно устанавливаются и исправить ошибку TypeError.