I have had a problem when tested polling function using setTimeout()
.
I found a hint to solve this problem and it helps me to understand what problem is.
Following code is the proof of concept. It works well.
Test Code
- Log Sequence -
3 > 1 > 4 > 2 > ... > 3 > 1 > 4 > 2 END
it('PoC Message queues, PromiseJobs and Mock Timers', async () => {
jest.useFakeTimers();
const callback = jest.fn();
PollingClient.pocPolling(callback, '/second-auth', {}, 1000);
// 6 times run
for (let i = 0; i < 6; i++) {
jest.advanceTimersByTime(1000); // message queue is resolved
console.log(1)
await Promise.resolve(); // `await` is resolved here
console.log(2)
}
expect(callback).toHaveBeenCalledTimes(6);
expect(callback).toHaveBeenLastCalledWith({data: true});
});
PoC Polling Function
const pocPolling = (callback, path, config, interval) => {
setTimeout(async () => {
try {
console.log(3);
const response = await new Promise((response) => response({data: true}));
console.log(4);
callback(response);
} catch (error) {
console.error(error);
}
pocPolling(callback, path, config, interval);
}, interval);
};
Following code is the problem I encountered.
Test code
- Log Sequence -
5 > 1 > 2 > 3 > 6 > 4 > ... > 5 > 1 > 2 > 3 > 6 > 4 END
it('guess something two wierd promises are made by axios.get method mocking', async () => {
jest.useFakeTimers();
const spyAxios = jest.spyOn(axios, 'get').mockResolvedValue({data: true});
const callback = jest.fn();
PollingClient.polling(callback, '/second-auth', {}, 1000);
// 6 times run
for (let i = 0; i < 6; i++) {
jest.advanceTimersByTime(1000); // message queue is resolved
console.log(1)
await Promise.resolve(); // something wierd promise
console.log(2)
await Promise.resolve(); // something wierd promise
console.log(3)
await Promise.resolve(); // `await` is resolved here
console.log(4)
}
expect(callback).toHaveBeenCalledTimes(6);
expect(callback).toHaveBeenLastCalledWith({data: true});
expect(spyAxios).toHaveBeenCalledTimes(6);
expect(spyAxios).toHaveBeenLastCalledWith('http://localhost:8080/second-auth', {});
});
Polling Function
const polling = (callback, path, config, interval) => {
setTimeout(async () => {
try {
console.log(5);
const response = await axios.get(`http://localhost:8080${path}`, config);
console.log(6);
callback(response);
} catch (error) {
console.error(error);
}
polling(callback, path, config, interval);
}, interval);
};
I don't understand the reason why I have to call Promise.resolve()
two times more to pass the test.
Where do Promises
come from?
I guess spyAxios mocked by jest.spyOn(axios, 'get') makes Promise internally when it is called.