I am trying to learn Jest(My jest version is 26). But, I am stuck on one problem regarding the behaviour of jest.runallTicks function.
Consider the following code (I am not directly using the console.log at the beginning of each function because I am not sure whether it is truly synchronous or not, instead I push the log to an array):
const arr: String[] = [];
const A = ()=>{
traceFunctionStart("A");
B().then(F);
return C();
}
const B = () => {
traceFunctionStart("B");
return D().then(E);
}
const C = () => {
traceFunctionStart("C");
return Promise.resolve();
};
const D = () => {
traceFunctionStart("D");
return Promise.resolve();
}
const E = () =>{
traceFunctionStart("E");
return Promise.resolve();
}
const X = () => {
traceFunctionStart("X");
return Promise.resolve();
}
const F = () => {
traceFunctionStart("F");
return X();
}
const traceFunctionStart = (x: string) => {
arr.push(x);
}
test("test", async ()=>{
jest.useFakeTimers();
await A();
jest.runAllTicks();
console.log(arr);
});
Expectation:
A gets called. Which calls B which calls D. Now, D returns a resolved promise. Hence, E gets added to the micro-queue.
B returns a pending promise. Hence, F does not get added to the micro queue just yet when control goes to line with B().then(F);.
C gets called and returned.
A is resolved and code moves to jest.runAllTicks, which forces the micro-task queue to be exhausted. The queue only contains E as of now. So, E gets called. And, it returns a resolved promise. Which means that the promise returned by B is resolved
which in turn means F gets added to the microtask queue. And, then, it should get called followed by X.
As a result, the order of execution(as given by the console output) must be: A->B->D->C->E->F->X.
Observed:
I observe that the output is the following:
[ 'A', 'B', 'D', 'C', 'E' ]
Where are F and X?
If I understand the documentation properly, the jest.runAllTicks() function should exhaust the micro task queue including the tasks that get added by these tasks themselves. Hence, F and X should be there.