javascript - 匹配器错误 : received value must be a mock or spy function

标签 javascript reactjs jestjs react-testing-library

我正在为表单 React 组件编写测试(使用 Jest 和 React 测试库)。我有一个在表单提交上运行的方法:

const onSubmit = (data) => {
  // ...
  setIsPopupActive(true);
  // ...
};
useEffectisPopupActive 之后运行改变,所以也提交:
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相关公关。
好吧,您可以通过两种方式解决您的问题。

  • 配置 Jest 以使用旧的假计时器。在 jest.config.js 您可以添加行(但它不适用于我):

  • 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/

    相关文章:

    javascript - 无法自动刷新内容

    reactjs - MapDispatchToProps 在父组件中导致 Typescript 错误,期望 Actions 作为 props 传递

    javascript - Jest 和 SCSS 变量

    reactjs - 在 Jest 中模拟 URQL 的获取状态

    javascript - 找不到名称 'ReadableStream'

    javascript - 在每个 Ember 环境中保留具有多个适配器的固定装置

    reactjs - 捆绑失败: Error: Cannot find module 'babel-preset-react-native-stage-0/decorator-support'

    javascript - 求助:ChartJS注释不显示

    typescript - Jest 模拟 moment()

    javascript - 在 AngularJS 中删除页面刷新/重新加载时的 $location 搜索