我真的很困惑尝试借助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?
任何帮助表示赞赏:)
我还没有真正测试过此代码。但是,我认为类似的事情应该起作用。
const fruits = ['banana', 'apple', 'orange', 'vodka', 'kiwi']; it('mock setTimeout test', () => { jest.useFakeTimers(); setTimeout(() => { expect(component.state().fruits).toEqual(fruits); }, 1500); jest.runAllTimers(); });