After user click login, I need check the server status every 3 seconds. After 20 times check, display timeout and clear the timer.
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. 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.
For a setInterval that runs continuously you'll want to use jest. advanceTimersByTime . import * as React from 'react'; import { MyComponent } from './code'; import { shallow } from 'enzyme'; test('MyComponent', () => { jest. useFakeTimers(); const component = shallow(<MyComponent/>); expect(component.
Enable Fake TimersuseFakeTimers() . This is replacing the original implementation of setTimeout() and other timer functions. Timers can be restored to their normal behavior with jest.
setTimeout(timeout) Set the default timeout interval for tests and before/after hooks in milliseconds. Note: The default timeout interval is 5 seconds if this method is not called. Example: jest.
beforeEach(fn, timeout) Runs a function before each of the tests in this file runs. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running the test. Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before aborting.
Use jest.advanceTimersByTime to advance your timer and test in your test file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With