小编典典

玩笑反应测试:延迟后检查状态

reactjs

我真的很困惑尝试借助Jest文档https://facebook.github.io/jest/docs/timer-
mocks.html#content创建测试

我尝试检查容器挂载时的状态,然后在我手动设置状态值(使用setTimeout())之后几秒钟。

我在Main的componentDidMount内部有一个函数,如下所示:

componentDidMount() {
    this.setStateAfterDelay();
}

该函数的作用是:

setStateAfterDelay = () => {
    setTimeout(() => {
        this.setState({ fruits: ['banana', 'apple', 'orange', 'vodka', 'kiwi'] });
    }, 1500);
}

我达到了第一部分:

const component = mount(<Main />);
expect(component.state().fruits).toEqual(null);

但是我不知道以后如何再次检查状态,比如说2000ms?

任何帮助表示赞赏:)


阅读 239

收藏
2020-07-22

共1个答案

小编典典

我还没有真正测试过此代码。但是,我认为类似的事情应该起作用。

const fruits = ['banana', 'apple', 'orange', 'vodka', 'kiwi'];

it('mock setTimeout test', () => {
 jest.useFakeTimers();
 setTimeout(() => {
   expect(component.state().fruits).toEqual(fruits);
 }, 1500);
 jest.runAllTimers();
});
2020-07-22