【问题标题】:How to test the order of ASYNC Requests with Jest如何使用 Jest 测试 ASYNC 请求的顺序
【发布时间】:2018-08-25 17:59:20
【问题描述】:

我需要测试一系列异步函数是否按特定顺序调用。有没有简单的方法可以做到这一点?

下面是我想要实现的示例:

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 类 [此处](我编写了一个模块,该模块接受一个函数和一个优先级对象,然后将其添加到队列中,在该队列中根据优先级按顺序调用任务。我需要测试的函数确实是按顺序调用的。上下文请查看下面module中的TaskQueue
  • 更新为完整的link

标签: javascript node.js testing promise jestjs


【解决方案1】:

一种方法如下:

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]);
});

它在每个 promise 之后将值推送到一个数组中,一旦它们都解决了,就按照预期的顺序测试 result 数组中值的顺序。

【讨论】:

    猜你喜欢
    • 2019-06-16
    • 2015-12-21
    • 2020-05-15
    • 2021-08-11
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 2019-01-03
    相关资源
    最近更新 更多