Node.js 异步函数的chai测试失败,引发错误
我想测试一下我的“失踪尸体”是否被扔了。但是我的测试只显示已捕获的错误,但是expect测试仍然失败。你能帮我理解吗Node.js 异步函数的chai测试失败,引发错误,node.js,async-await,mocha.js,chai,Node.js,Async Await,Mocha.js,Chai,我想测试一下我的“失踪尸体”是否被扔了。但是我的测试只显示已捕获的错误,但是expect测试仍然失败。你能帮我理解吗 async add(req) { const db = _.get(req, 'app.locals.db'); const bookDescription = req.body; logger.info('books.add', bookDescription); if (_.isEmpty(bookDescription)) { throw
async add(req) {
const db = _.get(req, 'app.locals.db');
const bookDescription = req.body;
logger.info('books.add', bookDescription);
if (_.isEmpty(bookDescription)) {
throw new Error('missing_body');
}
[...]
}
describe('+add(req)', function() {
it('should fail because of missing body', async function() {
const req = {
body: {},
};
expect(await this.ctrl.add(req)).to.throw(new Error('missing_body'));
});
});
如果希望捕获某些错误,则需要在捕获块内断言。您正在尝试断言一个arror,并创建一个新的错误实例。如果您使用的是同步编程,则需要捕获错误,如:
it('should fail because of missing body', async function() {
const req = {
body: {},
};
try {
await this.ctrl.add(req)
} catch(e) {
expect(e.message).to.equal('missing_body');
}
});
另一个错误是提供一个对象方法(或任何依赖于此的独立函数)作为断言的目标。这样做是有问题的,因为当.throw调用函数时,此上下文将丢失;它不可能知道这是什么。解决这个问题有两种方法。一种解决方案是将方法或函数调用封装在另一个函数中。另一个解决方案是使用bind。如果你测试同步功能
expect(function () { cat.meow(); }).to.throw(); // Function expression
expect(() => cat.meow()).to.throw(); // ES6 arrow function
expect(cat.meow.bind(cat)).to.throw(); // Bind
但是在异步(wait add()).to.throw(Error)
将永远不会工作:如果fails()拒绝,则抛出错误,并且永远不会执行.to.throw(Error)。所以你需要这样做:
it('should fail', async () => {
await expect(this.ctrl.add(req.body)).to.be.rejectedWith(Error);
})
解决方案:
async add(req) {
const db = _.get(req, 'app.locals.db');
const bookDescription = req.body;
logger.info('books.add', bookDescription);
if (_.isEmpty(bookDescription)) {
throw new Error('missing_body');
}
[...]
}
describe('+add(req)', function() {
it('should fail because of missing body', async function() {
const req = {
body: {},
};
await expect(this.ctrl.add(req.body)).to.be.rejectedWith(Error);
});
});
如果u.empty返回true,这不是错误,这就是我要检查的。所以在我的测试中,我将坚持使用
this.ctrl.add(req)
。我做错的是,把我的等待放在期望中,而不是期望上。谢谢你解决了我的问题!