我需要测试一系列异步函数是否按特定顺序调用。有没有简单的方法可以做到这一点?
下面是我想要实现的示例:
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 ????? */
})
})
最佳答案
一种方法如下:
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
数组中值的顺序。
关于javascript - 如何用 Jest 测试 ASYNC 请求的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49324618/