Mock setInterval method in react using jest test cases

13,700

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.

Share:
13,700
prabhakaran s
Author by

prabhakaran s

Updated on July 05, 2022

Comments

  • prabhakaran s
    prabhakaran s almost 2 years

    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();
    })
    
  • Menai Ala Eddine - Aladdin
    Menai Ala Eddine - Aladdin over 3 years
    How to call state in Functional Compoents ?