[英]How to write a Unit test for inserting and retrieving an object to mongodb using mongoose, mocha and chai?
I'm trying to write a unit test for inserting (and then retrieving) a document to mongodb. 我正在尝试编写用于将文档插入(然后检索)文档到mongodb的单元测试。 However, I keep getting a timeout error, and it suggests that done
is never called. 但是,我一直收到超时错误,这表明从不调用done
。 (Mongod is running, and I can see the objects being inserted just fine as well as being retrieved, using console.log.) (Mongod正在运行,我可以使用console.log看到插入的对象以及被检索的对象。)
What I'm using: 我正在使用什么:
Node.js, ES6, Mongoose, Mocha, Chai Node.js,ES6,猫鼬,摩卡,柴
CheckbookEntry is a weird wrapper to some Mongoose calls that let's me work with promises. CheckbookEntry是对某些Mongoose调用的怪异包装,让我凭承诺工作。
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
Any suggestions on how to get this working? 关于如何使它工作的任何建议?
I can only guess, but I think that the problem may be caused by this: 我只能猜测,但是我认为问题可能是由以下原因引起的:
.then(function(foundEntry){
expect(foundEntry).to.eql(EXAMPLE_ENTRY);
done();
}, function(err){
assert.fail(err);
done();
});
More specifically, using assertions in a fulfilled/rejection handler without continuing the promise chain. 更具体地说,在未完成承诺链的情况下在已完成/拒绝处理程序中使用断言。
If the assertion throws an exception, done()
will never get called. 如果断言引发异常,则done()
将永远不会被调用。 And depending on which promise implementation is being used, you might never even get notified about the exception. 并且取决于所使用的Promise实现,您甚至可能永远都不会收到有关该异常的通知。 Also, an exception thrown in the onFulFilled
handler won't trigger the onRejected
handler passed to the same .then()
method. 同样,在onFulFilled
处理程序中引发的异常不会触发传递给相同onRejected
.then()
方法的onRejected
处理程序。
Because Mocha supports promises out of the box , instead of using the done
callback, return your promise chain: 因为Mocha 支持开箱即用的Promise ,而不是使用done
回调,所以返回您的Promise链:
return CheckbookEntry.create(...)
.then(...)
.then(..., ...);
That way, the exception will get propagated back to Mocha, which will handle it. 这样,异常将传播回Mocha,Mocha将对其进行处理。
FWIW, Mongoose also supports promises out of the box . FWIW,猫鼬还支持开箱即用的承诺 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.