async http request breaks fake-timers

20 views Asked by At

I need to combine simulated discrete time events that I faked with fake-timers with real http requests. Here is an example code

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();

Thanks

the expected output should be

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

But I get

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

Is there any way for the fake-timer to wait for the async code to finsh even if it takes quite a long time

1

There are 1 answers

0
CornFlow On

Have figured it out if anyone would need it. The solution loop time through ticks one by one and each time waits for all the promises to resolve. Also, the async promises need to be buffered as shown below

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();

this outputs

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