Search code examples
javascriptjasminejestjs

Disable Jest setTimeout mock


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?


Solution

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

      jest.useRealTimers()