Jest 反应测试:延迟后检查状态 [英] Jest react testing: Check state after delay

查看:25
本文介绍了Jest 反应测试:延迟后检查状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很困惑在 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);
}

我完成了第一部分:

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

但我不知道如何在 2000 毫秒后再次检查状态?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆