Jest反应测试:延迟后检查状态 [英] Jest react testing: Check state after delay
问题描述
我真的很困惑,试图在Jest文档的帮助下创建测试 https://facebook.github.io/jest/docs/timer-mocks.html#content
I'm really confused trying to create test with the help of Jest documentation https://facebook.github.io/jest/docs/timer-mocks.html#content
我正试图检查一个州当容器挂载,然后几秒钟之后,我在状态下手动设置值(使用setTimeout())。
I'm trying to check a state when container mounts and then few seconds later, after I have manually set values in the state (using setTimeout()).
我在Main的componentDidMount中有一个函数,如下所示:
I have a function inside Main's componentDidMount like this:
componentDidMount() {
this.setStateAfterDelay();
}
该功能的作用是:
setStateAfterDelay = () => {
setTimeout(() => {
this.setState({ fruits: ['banana', 'apple', 'orange', 'vodka', 'kiwi'] });
}, 1500);
}
我通过以下方式实现了第一部分:
I achieved the first part with:
const component = mount(<Main />);
expect(component.state().fruits).toEqual(null);
但我不知道如何再次检查状态,比方说2000ms?
But I have no clue how to check the state again after, lets say 2000ms?
感谢任何帮助:)
推荐答案
我还没有真正测试过此代码。但是,我认为类似的东西应该可行。
I haven't really tested this code. But, something similar to this should work I think.
const fruits = ['banana', 'apple', 'orange', 'vodka', 'kiwi'];
it('mock setTimeout test', () => {
jest.useFakeTimers();
setTimeout(() => {
expect(component.state().fruits).toEqual(fruits);
}, 1500);
jest.runAllTimers();
});
这篇关于Jest反应测试:延迟后检查状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!