我正在尝试编写一个单元测试,用于将文档插入(然后检索)到 mongodb。但是,我不断收到超时错误,它表明从未调用 done
。 (Mongod 正在运行,我可以使用 console.log 看到对象被插入以及被检索。)
我正在使用什么:
Node.js, ES6, Mongoose , Mocha 、 Chai
CheckbookEntry 是一些 Mongoose 调用的奇怪包装器,让我可以使用 Promise。
describe('create and getOneById', () => {
it('creates a new checkbookEntry, and retrieves it from the db', (done) => {
var EXAMPLE_ENTRY = {
type: 'debit',
date: Date(),
description: 'Example of a cb entry',
account: 'PNC',
amount: 239.33
};
CheckbookEntry.create(EXAMPLE_ENTRY.type,
EXAMPLE_ENTRY.date,
EXAMPLE_ENTRY.description,
EXAMPLE_ENTRY.account,
EXAMPLE_ENTRY.amount)
.then(function(createdEntry){
return CheckbookEntry.getOneById(createdEntry._id);
})
.then(function(foundEntry){
expect(foundEntry).to.eql(EXAMPLE_ENTRY);
done();
}, function(err){
assert.fail(err);
done();
});
}).timeout(5000);
}); // end describe create
关于如何让它发挥作用有什么建议吗?
最佳答案
我只能猜测,但我认为问题可能是这样造成的:
.then(function(foundEntry){
expect(foundEntry).to.eql(EXAMPLE_ENTRY);
done();
}, function(err){
assert.fail(err);
done();
});
更具体地说,在完成/拒绝处理程序中使用断言而不继续 promise 链。
如果断言抛出异常,done()
将永远不会被调用。根据所使用的 Promise 实现,您可能永远不会收到有关异常的通知。此外,onFulFilled
处理程序中引发的异常不会触发传递给同一 .then()
方法的 onRejected
处理程序。
因为 Mocha supports promises out of the box ,不要使用 done
回调,而是返回您的 promise 链:
return CheckbookEntry.create(...)
.then(...)
.then(..., ...);
这样,异常就会传播回 Mocha,Mocha 将处理它。
FWIW, Mongoose also supports promises out of the box .
关于javascript - 如何使用 mongoose、mocha 和 chai 编写单元测试来向 mongodb 插入和检索对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38032832/