【问题标题】:Mock setInterval method in react using jest test cases使用笑话测试用例模拟 setInterval 方法
【发布时间】:2019-09-23 16:15:15
【问题描述】:

我想模拟 setInterval 方法,并且应该覆盖 getData 方法中的行。 有人可以帮我解决这个问题吗?

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

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

我试过了

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

【问题讨论】:

    标签: reactjs mocking jestjs setinterval


    【解决方案1】:

    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

    【讨论】:

    • 如何在函数式组件中调用状态?
    猜你喜欢
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 2019-03-26
    • 2021-10-30
    • 2022-12-22
    相关资源
    最近更新 更多