如果使用try-catch包装异步函数,即使断言失败,mocha测试也会通过



如果没有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

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

例如,如果你查看mocha的文档,你会看到:

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没有发现任何异常,认为没有问题,并且测试被标记为通过。

最新更新