如何使用Jest测试ASYNC请求的顺序

can*_*ton 1 javascript testing node.js promise jest

我需要测试是否以特定顺序调用了一系列异步函数。是否有捷径可寻?

下面是我要实现的示例:

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 ????? */
    })
})
Run Code Online (Sandbox Code Playgroud)

str*_*str 5

一种方法如下:

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]);
});
Run Code Online (Sandbox Code Playgroud)

每次承诺后,它将值推入数组,一旦所有值都解决,就result对照预期顺序测试数组中值的顺序。