我需要测试一系列异步函数是按特定顺序调用的。有一个简单的方法吗?
我想在下面实现的一个例子:
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 ????? */
})
})
答案 0 :(得分:3)
一种方法是:
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
数组中值的顺序。