javascript - 开 Jest : how to test setInterval

标签 javascript reactjs unit-testing jestjs

用户点击登录后,我需要每3秒检查一次服务器状态。检查20次后,显示超时并清除定时器。

我的代码:

onCheckStatus = () => {
    MAX_POLLING_COUNT = 20;
    this.timer = setInterval(() => {
        if (MAX_POLLING_COUNT > 0) {
            MAX_POLLING_COUNT -= 1;
            loginStatus(this.state.sessionId).then(
                res => {
                    const { goto, sessionId, errorMessageCode, result, hint } = res;
                    ........
                    if (goto === 'SUCCESS') {
                        this.setState({
                            messageInfo: {
                                type: 'success',
                                title: '',
                                description: result.description,
                            },
                        });
                    } else if (goto === 'ERROR') {

                    } 
                },
                () => {
                    clearInterval(this.timer);
                    this.setState({ error: true, loading: false });
                }
            );
        } else {
            this.setState({ error: true, loading: false });
        }
    }, 3000);
};

测试代码:

    jest.useFakeTimers();
    const wrapper = shallow(
        <AddGPForm step="GP_SIGNIN" uuid="testuuid" {...props} />
    );

    const form = shallow(wrapper.prop('children')(getMockFormApi(wrapper)));
    form.find('Login').simulate('submit', {
        reqestBody: '10x010101x0101x0101x10x0',
    });
    jest.runAllTimer();
    // jest.runTimersToTime(60000);
    // jest.runOnlyPendingTimers();

onCheckStatus将被触发,定时器内的代码从未被触发。我尝试将计时器内部的逻辑选择为单一方法。

新代码:

onCheckStatus = () => {
    this.timer = setInterval(this.check(), 3000);
}

检查方法仅被触发一次。

最佳答案

使用jest.advanceTimersByTime提前计时器并在测试文件中进行测试。

关于javascript - 开 Jest : how to test setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51354596/

相关文章:

python - Nose 不运行 Django doctests

java - 在Junit测试中,如何使用assertEquals()比较两个ArrayList<Double>,是否有更好的替代方案?

javascript - 枚举对象作为字典键

JavaScript (Postgres DB) - 如何在 WHERE IN ( ) 子句中使用带有数组作为参数的准备语句

javascript - 滑动时禁用网页导航(后退和前进)

javascript - 在 JavaScript/HTML 中嵌套引号

ios - React-Native Spotify SDK iOS : Dismiss auth window

reactjs - 如何在 Typescript 模块 (.tsx) 中导入在 JSX 中定义的现有 React 组件

javascript - 如何单独更新antd复选框组中的复选框

python - 如何在嵌套类中模拟实例变量