我正在为表单 React 组件编写测试(使用 Jest 和 React 测试库)。我有一个在表单提交上运行的方法:
const onSubmit = (data) => {
// ...
setIsPopupActive(true);
// ...
};
和 useEffect
在 isPopupActive
之后运行改变,所以也提交:useEffect(() => {
if (isPopupActive) {
setTimeout(() => {
setIsPopupActive(false);
}, 3000);
}
}, [isPopupActive]);
在测试中,我想检查弹出窗口是否在 3 秒后消失。所以这是我的测试:it('Closes popup after 3 seconds', async () => {
const nameInput = screen.getByPlaceholderText('Imię');
const emailInput = screen.getByPlaceholderText('Email');
const messageInput = screen.getByPlaceholderText('Wiadomość');
const submitButton = screen.getByText('Wyślij');
jest.useFakeTimers();
fireEvent.change(nameInput, { target: { value: 'Test name' } });
fireEvent.change(emailInput, { target: { value: 'test@test.com' } });
fireEvent.change(messageInput, { target: { value: 'Test message' } });
fireEvent.click(submitButton);
const popup = await waitFor(() =>
screen.getByText(/Wiadomość została wysłana/)
);
await waitFor(() => {
expect(popup).not.toBeInTheDocument(); // this passes
expect(setTimeout).toHaveBeenCalledTimes(1);
expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 3000);
});
});
但是,我收到了错误:expect(received).toHaveBeenCalledTimes(expected)
Matcher error: received value must be a mock or spy function
Received has type: function
Received has value: [Function setTimeout]
我究竟做错了什么?
最佳答案
开 Jest 27 对 fakeTimers 进行了重大更改。似乎 Jest 贡献者没有按时更新文档。 This对 Github 问题的评论证实了这一点。此外,here相关公关。
好吧,您可以通过两种方式解决您的问题。
module.exports = {
// many of lines omited
timers: 'legacy'
};
jest.useFakeTimers('legacy');
describe('My awesome logic', () => {
// blah blah blah
});
最好使用基于 @sinonjs/fake-timers 的新语法.但我找不到 的工作示例开 Jest ,所以我会尽快更新这个答案。
关于javascript - 匹配器错误 : received value must be a mock or spy function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68016538/