如何使用 mongoose、mocha 和 chai 编写用于将对象插入和检索到 mongodb 的单元测试?
How to write a Unit test for inserting and retrieving an object to mongodb using mongoose, mocha and chai?
我正在尝试编写用于将文档插入(然后检索)到 mongodb 的单元测试。但是,我一直收到超时错误,它表明 done
从未被调用过。 (Mongod 是 运行,我可以看到使用 console.log 插入和检索的对象都很好。)
我在用什么:
Node.js,
ES6,
猫鼬,
摩卡,
柴
CheckbookEntry 是一些 Mongoose 调用的奇怪包装器,让我可以使用 promises。
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();
});
更具体地说,在 fulfilled/rejection 处理程序中使用断言而不继续承诺链。
如果断言抛出异常,done()
将永远不会被调用。根据使用的是哪个 promise 实现,您甚至可能永远不会收到有关异常的通知。此外,onFulFilled
处理程序中抛出的异常不会触发传递给相同 .then()
方法的 onRejected
处理程序。
因为 Mocha supports promises out of the box,而不是使用 done
回调,return 您的承诺链:
return CheckbookEntry.create(...)
.then(...)
.then(..., ...);
这样,异常将传播回 Mocha,后者将处理它。
我正在尝试编写用于将文档插入(然后检索)到 mongodb 的单元测试。但是,我一直收到超时错误,它表明 done
从未被调用过。 (Mongod 是 运行,我可以看到使用 console.log 插入和检索的对象都很好。)
我在用什么:
Node.js, ES6, 猫鼬, 摩卡, 柴
CheckbookEntry 是一些 Mongoose 调用的奇怪包装器,让我可以使用 promises。
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();
});
更具体地说,在 fulfilled/rejection 处理程序中使用断言而不继续承诺链。
如果断言抛出异常,done()
将永远不会被调用。根据使用的是哪个 promise 实现,您甚至可能永远不会收到有关异常的通知。此外,onFulFilled
处理程序中抛出的异常不会触发传递给相同 .then()
方法的 onRejected
处理程序。
因为 Mocha supports promises out of the box,而不是使用 done
回调,return 您的承诺链:
return CheckbookEntry.create(...)
.then(...)
.then(..., ...);
这样,异常将传播回 Mocha,后者将处理它。