[英]Jest: how to test setInterval
After user click login, I need check the server status every 3 seconds.用户单击登录后,我需要每 3 秒检查一次服务器状态。 After 20 times check, display timeout and clear the timer.
检查 20 次后,显示超时并清除计时器。
my code:我的代码:
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);
};
test code:测试代码:
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 will be triggered, the the codes inside the timer never trigged. onCheckStatus 将被触发,计时器内的代码从未触发。 I tried to pick the logic inside the timer as one single method.
我试图将计时器内部的逻辑作为一种方法。
new code:新代码:
onCheckStatus = () => {
this.timer = setInterval(this.check(), 3000);
}
check method only be triggered once. check 方法只被触发一次。
使用jest.runAllTimers()
而不是jest.runAllTicks()
使用jest.advanceTimersByTime提前您的计时器并在您的测试文件中进行测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.