开玩笑:如何测试setInterval

时间:2018-07-16 04:27:59

标签: 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);
}

检查方法只能触发一次。

2 个答案:

答案 0 :(得分:0)

使用jest.runAllTimers();而不是jest.runAllTicks();

答案 1 :(得分:0)

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

相关问题