Mock setInterval method in react using jest test cases
Asked Answered
E

1

7

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();
})
Evildoer answered 6/5, 2019 at 2:49 Comment(0)
E
28

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.

Eminent answered 6/5, 2019 at 12:20 Comment(1)
How to call state in Functional Compoents ?Audiogenic

© 2022 - 2024 — McMap. All rights reserved.