【发布时间】:2020-01-17 08:46:40
【问题描述】:
我有一个请求数据的组件。成功获取数据后应显示通知。出于这个原因,我们有一个名为 @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 函数的反应钩子?
【问题讨论】:
标签: reactjs unit-testing jestjs