异步 HTTP 请求中断假计时器

async http request breaks fake-timers

提问人:CornFlow 提问时间:11/9/2023 更新时间:11/9/2023 访问量:14

问:

我需要将我伪造的模拟离散时间事件与假计时器与真实的 http 请求相结合。下面是一个示例代码

const FakeTimers = require("@sinonjs/fake-timers");
const clock = FakeTimers.install();

const axios = require('axios');

let fun = async () => {
    setTimeout(async function () {
        console.log(+new Date()+' Timer for 1000ms fired');
        await axios.get('https://jsonplaceholder.typicode.com/todos/1');
        console.log(+new Date() + ' Response');
    }, 1000);

    setTimeout(function () {
        console.log(+new Date()+' Timer for 2000ms fired');
       
    }, 2000);

    // Tick the clock to 1000ms and wait for any operations to finish.
    await clock.tickAsync(1000);

    // Tick the clock to 2000ms and wait for any operations to finish.
    await clock.tickAsync(1000);
}
fun();

谢谢

预期输出应为

1000 Timer for 1000ms fired
1000 Response
2000 Timer for 2000ms fired

但我明白了

1000 Timer for 1000ms fired
2000 Timer for 2000ms fired
2000 Response

有没有办法让假计时器等待异步代码关闭,即使需要相当长的时间

httprequest 模拟 asynchronous-javascript usefaketimers

评论


答:

0赞 CornFlow 11/9/2023 #1

如果有人需要它,已经弄清楚了。解决方案将时间逐个循环,每次都等待所有承诺解决。此外,异步承诺需要缓冲,如下所示

const FakeTimers = require("@sinonjs/fake-timers");
const clock = FakeTimers.install();

const axios = require('axios');

let promises=[]

let fun = async () => {
    setTimeout(async function () {
        console.log(+new Date()+' Timer for 1000ms fired');
        promises.push(axios.get('https://jsonplaceholder.typicode.com/todos/1'));
        console.log(+new Date() + ' Response');
    }, 1000);

    setTimeout(function () {
        console.log(+new Date()+' Timer for 2000ms fired');
      
    }, 2000);

    for (let i = 0; i < 3000; i++) {
        await clock.tickAsync(1)
        await Promise.all(promises);

    }
}
fun();

这输出

1000 Timer for 1000ms fired
1000 Response
2000 Timer for 2000ms fired