I have created below function for polling
export const wait = (ms: number): Promise<void> =>
new Promise((resolve) => setTimeout(resolve, ms));
/**
*
* @param {*} fn async function which will return result
* @param {*} cb callback to verify result for expected result. Return boolean value true to stop polling.
* @param {*} ms polling time
* @returns
*/
export async function polling<T>(
fn: () => Promise<T>,
cb: (res: T) => boolean,
ms: number
): Promise<T> {
try {
const res = await fn();
if (cb(res)) {
return res;
}
await wait(ms);
return polling(fn, cb, ms);
} catch (error) {
throw error;
}
}
For which I have written specs as
it('should poll for 5 times', async () => {
jest.useFakeTimers();
let count = 0;
const fn = () => {
count += 1;
return count;
};
const cb = (res) => res === 5;
const resP = polling(fn, cb, 1);
jest.runAllTimers();
const res = await resP;
jestExpect(res).toBe(6);
});
as shown in the above code I am using jest fakeTimer and still getting the below error
I have also tried keeping jest.useFakeTimers();
global scope but still getting the same error.
● Test Data Science Common Utility functions › should poll 5 times
: Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error:
95 | });
96 |
> 97 | it('should poll for 5 times', async () => {
| ^
98 | jest.useFakeTimers();
99 | let count = 0;
100 | const fn = () => {
I am new to writing the specs, The specs I have written above might be completely wrong. So correct spec for the above polling function will be appreciated.