Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0125· OpenAIAi2 WildChat-4.8M (AI2)

Вот у меня есть хук, который возвращает две функции. Как мне замокать его и проверить,…

  1. User

    Вот у меня есть хук, который возвращает две функции. Как мне замокать его и проверить, что при определенном условии вызывается одна из функций из хука?

  2. 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 - нет.

  3. 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();
    });
    

    });

    Не работает

  4. Assistant

    Чтобы правильно замокать хук useUploadDownloadGraphPanel в данном тесте, проверьте несколько моментов:

    1. Убедитесь, что импорт хука useUploadDownloadGraphPanel в файле UploadDownloadGraphPanel правильный.
    2. Убедитесь, что путь к импорту хука в тесте совпадает с путем в файле UploadDownloadGraphPanel.
    3. Проверьте, что хук 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 при клике на ссылку.

  5. 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();
    });
    

    }); второй раз не мокается, скажи почему

  6. 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, что позволит корректно провести тестирование второго теста.

  7. User

    TypeError: Cannot destructure property 'sumTitle' of '(0 , _model.useGetCurrencyTitle)(...)' as it is undefined. не работает, ошибка

  8. 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.