I want to mock setInterval method and should cover the lines insed the getData method. Can someone please help me on this.
startInterval() {
setInterval(() => this.getData(), this.state.timeInterval);
}
getData(){
// i want to covet this lines
}
I have tried as bellow
it('should call getTopIntentsSince', () => {
jest.useFakeTimers();
jest.runAllTicks();
})
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.
The native timer functions (i.e., setTimeout() , setInterval() , clearTimeout() , clearInterval() ) are less than ideal for a testing environment since they depend on real time to elapse. Jest can swap out timers with functions that allow you to control the passage of time.
setInterval is a method that calls a function or runs some code after specific intervals of time, as specified through the second parameter. For example, the code below schedules an interval to print the phrase: “Interval triggered” every second to the console until it is cleared.
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
.
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