6
votes

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
Jest 15 appears to disable timer mocks by default facebook.github.io/jest/blog/2016/09/01/jest-15.html - Allyl Isocyanate

1 Answers

10
votes

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

  jest.useRealTimers()