简体   繁体   English

用玩笑进行测试时,setInterval 不起作用

[英]setInterval not working when testing with jest

I got a class on which I'm trying to run Jest tests.我有一个 class 我正在尝试运行 Jest 测试。 The class (not the test) is using an interval inside. class(不是测试)在内部使用间隔。 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.但是,似乎 class 本身的间隔没有被执行。 I put some console.logs and saw it does arrive to the point in code in which the interval is set like this:我放了一些 console.logs 并看到它确实到达了代码中设置间隔的点,如下所示:

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?这是为什么?

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.笑话 object 不需要导入。 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:在类的代码中,我有一行调用例如setInterval(action, 3000) ,在测试中我们将调用:

jest.advanceTimersByTime(3000);

Only then will the action of the interval be actually invoked.只有这样,间隔的action才会被实际调用。

Using jest.runOnlyPendingTimers() should also work for this, assuming you don't care about specific times and just want the currently-scheduled callbacks to be run.使用jest.runOnlyPendingTimers()也应该适用于此,假设您不关心特定时间并且只想运行当前计划的回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM