Disable Jest setTimeout mock

2019-05-03 09:12发布

问题:

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

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)
})

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

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

回答1:

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

  jest.useRealTimers()