【发布时间】:2022-01-16 18:56:49
【问题描述】:
我有一个 Jest 单元测试,它正在测试来自模拟 API 调用的错误,以确保错误消息显示在页面上。在我的实际文件中,我使用notistack 来显示错误消息。我没有显示完整的 API 请求,因为我认为它不相关,简而言之,如下:
myComponent.js:
import { useSnackbar } from 'notistack';
const myComponent = props => {
const { enqueueSnackbar } = useSnackbar()
//make an API call to an endpoint
...
if (response.ok) enqueueSnackbar("API Success", { variant: "success" });
else enqueueSnackbar("API Failed", { variant: "error" });
}
因此,我正在单元测试中测试上述内容。同样,我不会粘贴整个单元测试,因为我认为它不相关,但类似于:
myComponent.test.js
import { render, screen } from "@testing-library/react"
test("testing error message on API call", async () => {
// mock the API call to return a 500 <- this works fine
render(<myComponent />)
// ensure that the error message is displayed in the screen
expect(screen.queryByText(/API Failed/)).toBeInTheDocument();
});
执行上述操作,我得到一个错误:
TypeError: 无法解构 '(0 , _notistack.useSnackbar)(...)' 因为它是未定义的
如果我简单地包含以下内容,enqueueSnackbar() 将被定义,但测试仍然失败,因为消息是 null。
const mockEnqueue = jest.fn();
jest.mock('notistack', () => ({
...jest.requireActual('notistack'),
useSnackbar: () => {
return {
enqueueSnackbar: mockEnqueue
};
}
}));
但是,我什至不想模拟快餐栏,因为我想测试每个特定场景(有多个)的实际显示消息。
【问题讨论】:
标签: javascript reactjs unit-testing jestjs notistack