gpt4 book ai didi

javascript - 开 Jest : how to test setInterval

转载 作者:行者123 更新时间:2023-12-03 13:32:08 27 4
gpt4 key购买 nike

用户点击登录后,我需要每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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com