I need to test that a series of asynchronous functions are called in a particular order. Is there an easy way to do this?
An example of what I want to achieve below:
describe("Test ASYNC order", () => {
it("Calls in a particular order", () => {
const p1 = new Promise(resolve => setTimeout(resolve, 500));
const p2 = new Promise(resolve => setTimeout(resolve, 600));
const p3 = new Promise(resolve => setTimeout(resolve, 200));
/* How would I test that the order of the promises resolving is p3 then p1 then p2 ????? */
})
})
I need to test that a series of asynchronous functions are called in a particular order. Is there an easy way to do this?
An example of what I want to achieve below:
describe("Test ASYNC order", () => {
it("Calls in a particular order", () => {
const p1 = new Promise(resolve => setTimeout(resolve, 500));
const p2 = new Promise(resolve => setTimeout(resolve, 600));
const p3 = new Promise(resolve => setTimeout(resolve, 200));
/* How would I test that the order of the promises resolving is p3 then p1 then p2 ????? */
})
})
TaskQueue
class in the following module
– canaan seaton
Commented
Mar 16, 2018 at 15:51
One way to do that is the following:
test('Calls in a particular order', async () => {
const res = [];
const storeRes = index => res.push(index);
const p1 = new Promise(resolve => setTimeout(resolve, 500)).then(() => storeRes(1));
const p2 = new Promise(resolve => setTimeout(resolve, 600)).then(() => storeRes(2));
const p3 = new Promise(resolve => setTimeout(resolve, 200)).then(() => storeRes(3));
await Promise.all([p1, p2, p3]);
expect(res).toEqual([3, 1, 2]);
});
It pushes values to an array after each promise, and once all of them have resolved, tests the order of the values in the result
array against the expected order.
You can create and use a Deferred object, as described in Testing Promise Side Effects with Async/Await.
I would remend this over using setTimeout, as unless you are controlling clocks with jest.useFakeTimers
, setTimeout will increase the time it takes to execute your test.
class Deferred {
constructor() {
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
}
}
test('Calls in a particular order', async () => {
const res = [];
const storeRes = index => res.push(index);
const d1 = new Deferred();
d1.promise.then(() => storeRes(1));
const d2 = new Deferred();
d2.promise.then(() => storeRes(2));
const d3 = new Deferred();
d3.promise.then(() => storeRes(3));
d3.resolve();
d1.resolve();
d2.resolve();
await Promise.all([d1.promise, d2.promise, d3.promise]);
expect(res).toEqual([3, 1, 2]);
});