在我们的摩卡测试中,有时我们会出现错误并引发异常,并且当引发这些异常时,即使出现问题,也不会调用后续的断言并且我们的测试可能会通过。
.animate()
我们尝试将其包装在try catch中,如下所示:
// this would pass
it('adsf', async () => {
assert.equal(1,1)
var foo = undefined;
foo.hi(); // throw exception
assert.equal(1,2) // assert not called
});
,但 // this would fail, but not say why
it('adsf', async () => {
try {
assert.equal(1,1)
// var foo = undefined;
// foo.hi();
assert.equal(1,2)
} catch (err) {
assert.fail(err) // if fail, such as the 1,2 case above, the line number of the error is not shown
}
});
案例隐藏了一些失败的断言信息。如果有人有任何建议,将不胜感激。
答案 0 :(得分:1)
您的示例中的测试不会通过。在mocha中,如果在测试中调用的函数引发异常,则测试将失败。示例:
const assert = require('assert');
function foo() {
throw new Error('err');
}
describe('test', () => {
it('works', async () => {
foo();
console.log('came here');
});
});
$ npx mocha test.js
test
1) works
0 passing (6ms)
1 failing
1) test
works:
Error: err
at foo (test.js:8:9)
at Context.<anonymous> (test.js:13:11)
at processImmediate (internal/timers.js:439:21)
因此,在您的示例中,由于foo.hi
抛出TypeError
,因此它将被mocha捕获并显示为测试失败(执行不会真正达到断言,但是测试将显示为还是失败了。
我怀疑在您的情况下发生的事情是兑现承诺或拒绝承诺,例如以下示例之一:
function throwing() {
return new Promise((resolve, reject) => { throw new Error('err'); });
}
function rejecting() {
return new Promise((resolve, reject) => { reject(new Error('err')); });
}
describe('test', () => {
it('works', async () => {
throwing();
rejecting();
console.log('came here');
});
});
$ npx mocha test.js
test
came here
✓ works
[some UnhandledPromiseRejectionWarnings here]
1 passing (6ms)
这两个函数都不会被测试捕获,因为函数成功执行了返回promise的操作,并且测试块完成了,但是失败稍后发生。如果您的函数返回了一个Promise,只需在测试中await
对其进行检查,以确保您获得了Promise结果:
describe('test', () => {
it('works', async () => {
await throwing();
await rejecting();
console.log('came here');
});
});
$ npx mocha test.js
test
1) works
0 passing (6ms)
1 failing
1) test
works:
Error: err
at test.js:4:51
at new Promise (<anonymous>)
at throwing (test.js:4:10)
at Context.<anonymous> (test.js:13:11)
at processImmediate (internal/timers.js:439:21)