我想测试一种方法,该方法返回Promise.allSettled()
的结果并调用另一个函数返回promise。
我将问题简化为以下测试代码:
describe('Promise tests', () => {
it('should reject directly', async () => {
const f = jest.fn().mockRejectedValue(new Error('foo'));
const p = async () => await f();
// works
await expect(p).rejects.toThrow('foo');
});
it('should reject with allSettled', async () => {
const f = jest.fn().mockRejectedValue(new Error('foo'));
const p = async () => await f();
const results = await Promise.allSettled([p]);
expect(results[0].status).toBe('rejected'); // fulfilled - but why?
expect(results[0].reason).toBe('foo');
});
});
为什么第二种情况没有收到被拒绝的承诺?
答案 0 :(得分:2)
您快到了。 Promise.allSettled
希望收到一个Promises数组,而不是返回一个Promise的函数数组,这实际上是常量p
所做的。
只需致电p()
即可解决问题:
describe('Promise tests', () => {
it('should reject directly', async () => {
const f = jest.fn().mockRejectedValue(new Error('foo'));
const p = async () => await f();
// works
await expect(p()).rejects.toThrow('foo');
});
it('should reject with allSettled', async () => {
const f = jest.fn().mockRejectedValue(new Error('foo'));
const p = async () => await f();
const results = await Promise.allSettled([p()]);
expect(results[0].status).toBe('rejected'); // fulfilled - but why?
expect(results[0].reason).toBe('foo');
});
});
顺便:我的小子抱怨不必要的等待:-)