Как я могу издеваться над реактивным крючком, используя Jest? - PullRequest
0 голосов
/ 17 января 2020

У меня есть компонент, который запрашивает данные. После успешного извлечения данных должно отображаться уведомление. По этой причине у нас есть пакет (в рабочих пространствах пряжи), который называется @my-company/notifications.

import { useNotification } from '@my-company/notifications';

const ComponentWithDataFetching = () => {
  const {
    enqueueInfoNotification,
  } = useNotification();
  const {
    data,
  } = useQuery({
    onCompleted: () => {
      enqueueInfoNotification({ message: 'Data successfully fetch' });
    },
  })
}

Я бы хотел его протестировать

import { useNotification } from '@my-company/notifications';
import { render, fireEvent, act, wait } from '@testing-library/react';

jest.mock('@my-company/notifications', () => ({
  useNotification() {
    return {
      enqueueInfoNotification: jest.fn(),
    };
  },
}));

describe('<ComponentWithDataFetching />', () => {
  it('should enqueue info notification', async () => {
    const { getByTestId } = render(
      <TestSuitWrapper>
        <ComponentWithDataFetching />
      </TestSuitWrapper>,
    );

    expect(useNotification).toBeCalled();
  });
});

При выполнении тестов возникает ошибка: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Если удалить jest.mock, тест начинается без ошибок. Как я могу смоделировать ловушку реагирования для функции тестового вызова enqueueInfoNotification?

1 Ответ

1 голос
/ 17 января 2020

Что вы можете сделать, так это то, что вы можете смоделировать модуль @mycompany/notifications, и в тесте вы можете реализовать его, чтобы вернуть ложную функцию с именем enqueueInfoNotification и проверить, вызывается ли она или нет. Но вам также следует смоделировать useQuery, который вы можете сделать, используя apollo-реагирующее тестирование пакет

import { useNotification } from '@mycompany/notifications';
import { render, fireEvent, act, wait } from '@testing-library/react';

jest.mock('@astral-frontend/notifications');

describe('<ComponentWithDataFetching />', () => {
  it('should enqueue info notification', async () => {
    useNotification.mockReturnValue({
       enqueueInfoNotification: jest.fn()
    });

    render(
      <TestSuitWrapper>
        <ComponentWithDataFetching />
      </TestSuitWrapper>,
    );

    expect(useNotification.enqueueInfoNotification).toBeCalled();
  });
});

...