为什么嘲笑的开玩笑诺言不会被allSettled拒绝?

时间:2020-08-25 14:18:28

标签: javascript node.js ecmascript-6 jestjs es6-promise

我想测试一种方法,该方法返回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');
    });
  });

为什么第二种情况没有收到被拒绝的承诺?

  • node.js v14.3.0
  • jest v25.4.0

1 个答案:

答案 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');
    });
  });

顺便:我的小子抱怨不必要的等待:-)