Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setInterval not working when testing with jest

I got a class on which I'm trying to run Jest tests. The class (not the test) is using an interval inside. I'm trying to test it with some method I created in the test like this:

const syncWait = ms => 
    {
        const end = Date.now() + ms;
        while (Date.now() < end) continue;
    };
    let myObj = new MyClass(); //the constructor starts the interval
    syncWait(5500);
    expect(...

However, it seems like the interval from the class itself is not being executed. I put some console.logs and saw it does arrive to the point in code in which the interval is set like this:

this.intervalId = setInterval(() => this.sendIntervalMessage(), this.timeUntilSendMessages); //time here is 3000

however it simply won't execute even after the time of the interval has passed. Why is that?

like image 582
Yonatan Nir Avatar asked Jun 21 '26 08:06

Yonatan Nir


1 Answers

So for some reason checking time with jest won't work like that and you have to mock the passage of time.

You do it like this:

At the first line of the test I added this line:

jest.useFakeTimers();

The jest object doesn't need to be imported. It's automatically available in a jest test. This line means we are not using actual time, but rather gives us the option to simulate (mock) the passage of time.

While in the class's code I got a line calling for example setInterval(action, 3000), in the test we will call:

jest.advanceTimersByTime(3000);

Only then will the action of the interval be actually invoked.

like image 59
Yonatan Nir Avatar answered Jun 23 '26 20:06

Yonatan Nir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!