【问题标题】:Why is a mocked jest promise not rejected with allSettled?为什么 allSettled 不会拒绝一个嘲笑的笑话承诺?
【发布时间】:2020-12-14 06:22:01
【问题描述】:

我想测试一个方法,它返回Promise.allSettled() 的结果并调用另一个返回承诺的函数。

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

  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
  • 开玩笑 v25.4.0

【问题讨论】:

  • 你的第一个测试用例对我来说失败了:expect(p) vs. expect(p())。当p 返回一个承诺时,Promise.allSettled 应该是这样的:Promise.allSettled([p(), /* many more*/])

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


【解决方案1】:

你快到了。 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');
    });
  });

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

【讨论】:

  • 好的,非常感谢,知道了!不过,我的第一个案例仍然通过。我还将检查我需要添加到 eslint/recommended(加上 TypeScript)的规则
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 2019-02-15
  • 2016-11-07
  • 2011-02-09
  • 1970-01-01
  • 2021-09-21
相关资源
最近更新 更多