Jest 测试由于模拟函数而失败,尽管它已执行
Jest test fails due to mock function despite its execution
以下 Jest 单元测试:
const onSuccess = jest.fn(() => console.log("Boooboooo"));
render(
<Footer onSuccess={onSuccess}
/>
);
const approveButton = screen.getByRole("button", {name: "APPROVE"});
userEvent.click(approveButton);
expect(onSuccess).toHaveBeenCalled();
失败:
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
而 onSuccess
确实 运行:
console.log
Boooboooo
后两部分来自 Jest 日志。知道有什么问题吗?
似乎 onSuccess
函数被异步调用,这意味着在调用 onSuccess
函数之前调用断言函数。
让我们尝试使用 waitFor 助手来断言回调函数被调用:
userEvent.click(approveButton);
await waitFor(() => expect(onSuccess).toHaveBeenCalled());
以下 Jest 单元测试:
const onSuccess = jest.fn(() => console.log("Boooboooo"));
render(
<Footer onSuccess={onSuccess}
/>
);
const approveButton = screen.getByRole("button", {name: "APPROVE"});
userEvent.click(approveButton);
expect(onSuccess).toHaveBeenCalled();
失败:
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
而 onSuccess
确实 运行:
console.log
Boooboooo
后两部分来自 Jest 日志。知道有什么问题吗?
似乎 onSuccess
函数被异步调用,这意味着在调用 onSuccess
函数之前调用断言函数。
让我们尝试使用 waitFor 助手来断言回调函数被调用:
userEvent.click(approveButton);
await waitFor(() => expect(onSuccess).toHaveBeenCalled());