为什么 allSettled 没有拒绝嘲笑的开玩笑承诺?

Why is a mocked jest promise not rejected with allSettled?

我想测试 returns Promise.allSettled() 结果并调用 returns promises 的另一个函数的方法。

我将问题简化为以下测试代码:

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

为什么第二个案例没有收到被拒绝的承诺?

你快到了。 Promise.allSettled 期望收到一个 Promise 数组,而不是返回一个 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');
    });
  });

顺便说一下:我的 linter 抱怨不必要的等待 :-)