禁用Jest setTimeout mock [英] Disable Jest setTimeout mock

查看:269
本文介绍了禁用Jest setTimeout mock的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为依赖于websocket库的代码编写Jest测试。

I'm writing a Jest test for code that depends on a websocket library.

websocket库被模拟。我想发送一条消息,等待异步操作完成,然后检查响应。

The websocket library is mocked. I want to send a message, wait for async actions to complete, and check the response.

it('sends a message and gets a response', () => {
  processor(ws).sendMessage()  // do a bunch of async stuff, call websocket.sendMessage()
  setTimeout(() => {
    expect(ws.getResponse()).toEqual('all done')
  }, 100)
})

不幸的是因为Jest嘲笑setTimeout,setTimeout失败了。如果我运行 jest.runAllTimers(),则超时会立即发生,因此无法接收消息。

Unfortunately because Jest mocks setTimeout, setTimeout fails. If I run jest.runAllTimers(), the timeout happens instantaneously, so fails to pick up the message.

任何想法如何说服jest取消模拟setTimeout或Jasmine解决方法?

Any idea how to convince jest to unmock setTimeout, or a Jasmine workaround?

推荐答案

您可以在测试用例之前添加以下代码。它适用于Jest v14.1.0 -

You can add following code before test cases. It works for me in Jest v14.1.0 -

  jest.useRealTimers()

这篇关于禁用Jest setTimeout mock的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆