Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 875
Allyl Isocyanate Avatar asked Aug 11 '16 21:08

Allyl Isocyanate


People also ask

How do I change jest timeout?

Use Jest. Settimeout(Newtimeout) To Increase The Timeout Value, If This Is A Long-Running Test.” will be demonstrated using examples from the programming language. jest. setTimeout(30000);

What is jest fn ()?

The jest. fn method allows us to create a new mock function directly. If you are mocking an object method, you can use jest. spyOn . And if you want to mock a whole module, you can use jest.

How do you cover setInterval in jest?

For a setInterval that runs continuously you'll want to use jest. advanceTimersByTime . import * as React from 'react'; import { MyComponent } from './code'; import { shallow } from 'enzyme'; test('MyComponent', () => { jest. useFakeTimers(); const component = shallow(<MyComponent/>); expect(component.

How do you mock in Cleartimeout on jest?

In this case we enable fake timers by calling jest. useFakeTimers();. This will mock out setTimeout and other timer functions using mock functions. If you are running multiple tests inside of one file or describe block, you can call jest.


1 Answers

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

  jest.useRealTimers()
like image 53
zc05 Avatar answered Sep 20 '22 12:09

zc05