jest.runAllTicks
runs everything in the micro-task queue.
For a setInterval
that runs continuously you'll want to use jest.advanceTimersByTime
.
Here is a simple example:
code.js
import * as React from 'react';
export class MyComponent extends React.Component {
constructor(...args) {
super(...args);
this.state = { calls: 0, timeInterval: 1000 };
this.startInterval();
}
startInterval() {
setInterval(() => this.getData(), this.state.timeInterval);
}
getData() {
this.setState({ calls: this.state.calls + 1 });
}
render() { return null; }
}
code.test.js
import * as React from 'react';
import { MyComponent } from './code';
import { shallow } from 'enzyme';
test('MyComponent', () => {
jest.useFakeTimers();
const component = shallow(<MyComponent/>);
expect(component.state('calls')).toBe(0); // Success!
jest.advanceTimersByTime(3000);
expect(component.state('calls')).toBe(3); // Success!
})
If you cancel your interval so it doesn't run continuously then you can also use jest.runAllTimers
.