与mongojs进行集成测试以覆盖数据库错误 [英] Integration testing with mongojs to cover database errors
问题描述
我正在与mongojs
一起工作,并为mocha
进行测试,并使用istanbul
进行覆盖.我的问题是我想测试数据库错误.
I'm working with mongojs
and writing tests for mocha
running coverage with istanbul
. My issue is that I would like to include testing db errors.
var mongojs = require('mongojs');
var db = mongojs.connect(/* connection string */);
var collection = db.collection('test');
...
rpc.register('calendar.create', function(/*... */) {
collection.update({...}, {...}, function (err, data) {
if (err) {
// this code should be tested
return;
}
// all is good, this is usually covered
});
});
测试看起来像这样
it("should gracefully fail", function (done) {
/* trigger db error by some means here */
invoke("calendar.create", function (err, data) {
if (err) {
// check that the error is what we expect
return done();
}
done(new Error('No expected error in db command.'));
});
});
有一个相当复杂的设置脚本可以设置集成测试环境.当前的解决方案是使用db.close()
断开数据库连接并运行测试,从而导致所需的错误.当此后所有其他要求数据库连接的测试失败时,此解决方案就会出现问题,因为我尝试重新连接没有成功.
There is a fairly complex setup script that sets up the integration testing environment. The current solution is to disconnect the database using db.close()
and run the test resulting in an error as wanted. The problem with this solution arises when all the other tests after that require the database connection fail, as I try to reconnect without success.
关于如何巧妙地解决此问题的任何想法?最好不要编写下一个版本的mongojs
可能不会引发的自定义错误.还是有更好的方法来构建测试?
Any ideas on how to solve this neatly? Preferably without writing custom errors that might not be raised by next version of mongojs
. Or is there a better way of structuring the tests?
推荐答案
如何模拟处理mongo的库呢?
What about mocking the library that deals with mongo?
例如,假设db.update
最终是被collection.update
调用的函数,您可能想做类似的事情
For example, assuming db.update
is eventually the function that gets called by collection.update
you might want to do something like
describe('error handling', function() {
beforeEach(function() {
sinon.stub(db, 'update').yields('error');
});
afterEach(function() {
// db.update will just error for the scope of this test
db.update.restore();
});
it('is handled correctly', function() {
// 1) call your function
// 2) expect that the error is logged, dealt with or
// whatever is appropriate for your domain here
});
});
我使用了 Sinon
JavaScript的独立测试间谍,存根和模拟.没有依赖关系,可与任何单元测试框架一起使用.
Standalone test spies, stubs and mocks for JavaScript. No dependencies, works with any unit testing framework.
这有意义吗?
这篇关于与mongojs进行集成测试以覆盖数据库错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!