Ложный метод setInterval в реакции с использованием шутливых тестов - PullRequest
1 голос
/ 06 мая 2019

Я хочу смоделировать метод setInterval и должен охватывать строки, введенные методом getData. Может кто-нибудь, пожалуйста, помогите мне в этом.

startInterval() {
    setInterval(() => this.getData(), this.state.timeInterval);
}

getData(){
 // i want to covet this lines
}

Я пробовал как ниже

it('should call getTopIntentsSince', () => {
    jest.useFakeTimers();
    jest.runAllTicks();
})

1 Ответ

0 голосов
/ 06 мая 2019

jest.runAllTicks запускает все в очереди микро-задач.

Для setInterval, который работает непрерывно, вы захотите использовать jest.advanceTimersByTime.

Вот простой пример:

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!
})

Если вы отмените интервал, чтобы он не работал непрерывно, вы также можете использовать jest.runAllTimers.

...