Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock setInterval method in react using jest test cases

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();
})
like image 987
prabhakaran s Avatar asked May 06 '19 02:05

prabhakaran s


People also ask

How do you mock 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.

Can we use setTimeout in 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.

How does setInterval work in React?

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.


1 Answers

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.

like image 138
Brian Adams Avatar answered Sep 21 '22 12:09

Brian Adams