如何使用Jest模拟反应挂钩?

时间:2020-01-17 08:46:40

标签: reactjs unit-testing jestjs

我有一个请求数据的组件。成功获取数据后,应显示通知。因此,我们在纱线工作区中有一个名为@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函数的React钩子?

0 个答案:

没有答案