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?
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);
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.
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.
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.
You can add following code before test cases. It works for me in Jest v14.1.0 -
jest.useRealTimers()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With