【问题标题】:mocha test passes even when assertion fail if async function wrapped with try catch如果异步函数用 try catch 包装,即使断言失败,mocha 测试也会通过
【发布时间】:2021-04-21 03:44:13
【问题描述】:

没有try catch块,当有断言错误时测试正常失败

describe("POST /foo", function () {
  it('should create a foo', async function () {
      const response = await request.post("/foo").send(data);
      expect(response.status).to.eql(200); //Assertion error
  }).timeout(10000);
})
//+ expected - actual -500 + 200 1 failing

但是,如果我用 try/catch 块包装它,测试就会通过

describe("POST /foo", function () {
 it('should create a foo', async function () {  
    try {
       const response = await request.post("/foo").send(data);
        expect(response.status).to.eql(200); //Assertion error
      } catch (err) {
      }
    })
})
//1 passing

【问题讨论】:

    标签: node.js async-await mocha.js chai supertest


    【解决方案1】:

    断言库(如chai)具有expectassert 之类的函数,当它们检查的条件失败时会抛出异常。测试运行程序(在本例中为 mocha)可以通过在 try/catch 块中执行测试用例来使用此事实来检测测试失败。如果测试用例(即断言库)抛出异常,则认为测试失败。

    例如,如果您查看mocha's documentation,您会看到:

    Mocha 允许您使用任何您希望使用的断言库...通常, 如果它抛出一个错误,它会工作!

    所以在伪代码中,mocha 正在做类似的事情:

    function testRunner() {
      try {
        testCase('should create a foo'); // run a test case defined by the user
      } catch (e) {
        console.log('The test has failed');
        return;
      }
      console.log('The test has succeeded.');
    }
    

    如果您将测试用例中的所有代码包装在一个 try/catch 块中,就像在第二个示例中一样,您将阻止 mocha 看到断言库的 expect 语句引发的异常。 (您定义的 catch 块是“吞下”异常)。 mocha 没有发现异常,认为没有问题,测试被标记为通过。

    【讨论】:

      猜你喜欢
      • 2020-12-31
      • 2017-10-31
      • 2017-07-18
      • 2021-12-31
      • 1970-01-01
      • 2021-08-22
      • 2019-02-19
      • 2020-03-11
      • 1970-01-01
      相关资源
      最近更新 更多