【问题标题】:Jest - assert async function throws test fails开玩笑 - 断言异步函数抛出测试失败
【发布时间】:2020-03-11 10:15:26
【问题描述】:

得到以下失败的测试用例,我不知道为什么:

foo.js

async function throws() {
  throw 'error';
}

async function foo() {
  try {
    await throws();
  } catch(e) {
    console.error(e);
    throw e;
  }
}

test.js

const foo = require('./foo');

describe('foo', () => {
  it('should log and rethrow', async () => {
    await expect(foo()).rejects.toThrow();
  });
});

我希望 foo 抛出,但由于某种原因它只是解决了并且测试失败了:

FAILED foo › should log and rethrow - Received function did not throw

Live example

可能缺少异步等待抛出行为的一些基本细节。

【问题讨论】:

  • 不要等待它......只是expect(foo()).rejects.toThrow(); = 因为 foo 所做的只是返回一个拒绝的承诺......
  • @Bravo 这只是隐藏了问题,因为测试不等待结果。
  • 是的,我明白了......但你不希望(await foo()) 代替吗?我头晕了:p
  • @Bravo 是的,这很令人困惑,但这是测试抛出异步函数的方法:) https://stackoverflow.com/a/47887098/4341456

标签: javascript reactjs unit-testing jestjs


【解决方案1】:

似乎这是一个已知的错误:https://github.com/facebook/jest/issues/1700

这可行:

describe('foo', () => {
  it('should log and rethrow', async () => {
    await expect(foo()).rejects.toEqual('error')
  });
});

【讨论】:

    【解决方案2】:

    我认为您需要检查被拒绝的错误

    const foo = require('./foo');
    describe('foo', () => {
      it('should log and rethrow', async () => {
        await expect(foo()).rejects.toEqual('error');
      });
    });
    

    【讨论】:

    • 谢谢,不是 100% 确定它与投掷测试相同,但我想这是下一个最好的事情。最终选择了await expect(foo()).rejects.toBeTruthy();
    • 您还可以将您的代码调整为类似并且应该可以工作:async function throws() { throw new Error('error'); }
    • 谢谢!由于某种原因,手动抛出错误需要不同的语法
    【解决方案3】:

    当我不想使用 toEqualtoBe 时,我会使用此代码(就像其他正确答案一样)。相反,我使用toBeTruthy

    async foo() {
      throw "String error";
    }
    
    describe('foo', () => {
      it('should throw a statement', async () => {
        await expect(foo()).rejects.toBeTruthy();
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2020-10-08
      • 2019-05-17
      • 2022-01-01
      • 2017-02-11
      • 1970-01-01
      • 2021-08-22
      • 1970-01-01
      • 2019-04-01
      • 2018-02-13
      相关资源
      最近更新 更多