javascript - 如何使用 jest 在一定时间的模拟时间后运行断言测试?

标签 javascript unit-testing reactjs jestjs enzyme

假设我有一个组件,它呈现一个简单的 div,其中包含一个从 0 开始并每秒递增 1 的整数。因此,5 秒后,组件应呈现“5”,30 秒后,应呈现“30”,依此类推。如果我想测试这个组件并确保它在 5 秒后呈现出应有的效果,我可能会写这样的内容。

it('should render <5> after 5 seconds', () => {
  const time = mount(<Timer/>)
  setTimeout(() => {
    expect(time.text()).toEqual('5')
  }, 5000)
})

但是,这不起作用,因为测试从未真正运行预期并无论如何都返回通过。即使它确实有效,使用这样的超时也会非常低效,因为测试必须等待 5 秒钟。如果我想模拟更长的时间怎么办?经过一番搜索,我发现 jest 实际上有一个 timer mock但我似乎不知道如何在这种情况下实现它。任何帮助将不胜感激。谢谢!

最佳答案

为了让 Jest 知道您的测试是异步的,您需要:1) 返回 Promise,或 2) 在测试回调中声明一个参数,如下所示:

it('should render <5> after 5 seconds', done => {
  // test stuff
});

来源:https://facebook.github.io/jest/docs/en/asynchronous.html

为了让你的测试工作:

it('should render <5> after 5 seconds', done => {
  jest.useFakeTimers(); // this must be called before any async things happen

  const time = mount(<Timer/>);

  setTimeout(() => {
    // Note the placement of this try/catch is important.
    // You'd think it could be placed most anywhere, but nope...
    try {
      // If this assertion fails, an err is thrown.
      // If we do not catch()...done.fail(e) it,
      // then this test will take jasmine.DEFAULT_TIMEOUT_INTERVAL (5s unless you override)
      // and then fail with an unhelpful message.
      expect(time.text()).toEqual('5');
      done();
    } catch(e) {
      done.fail(e);
    }
  }, 5000);
  jest.runTimersToTime(5000); // This basically fast forwards 5s.
});

关于javascript - 如何使用 jest 在一定时间的模拟时间后运行断言测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40751534/

相关文章:

javascript - 如何使用watcher在eclipse中将ES6代码转换为ES5 java脚本

javascript - ajax 表单不起作用

scala play 框架如何对异步 Controller 进行单元测试

reactjs - 用 Enzyme 测试简单的 Redux-Form(值(value)在哪里??)

javascript - React Prop 在重新渲染时变得未定义

javascript - 如何将 Action 创建者分离到单独的文件中?

javascript - 在 java 脚本中的 setTimeout 方法内调用 setInterval 函数获取 setInterval(...) 不是函数错误

javascript - 使用 Ajax 和 JSON 在 HTML 中显示 PHP 回显消息

java - 在 IDEA 中运行 JUnit 方法的顺序错误

c# - 设置 Mock 以重定向到重载方法