Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest: how to test setInterval

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.

like image 345
Gary Wang Avatar asked Jul 16 '18 04:07

Gary Wang


People also ask

How do you mock setInterval in Jest?

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.

Which statement must be used to set fake timers before all the tests in a Jest javascript file?

Enable Fake Timers​useFakeTimers() . This is replacing the original implementation of setTimeout() and other timer functions. Timers can be restored to their normal behavior with jest.

What is Jest setTimeout?

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.

What is Jest beforeEach?

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.


1 Answers

Use jest.advanceTimersByTime to advance your timer and test in your test file.

like image 138
Abhinav Singi Avatar answered Sep 28 '22 05:09

Abhinav Singi