【问题标题】:Integration testing with mongojs to cover database errors使用 mongojs 进行集成测试以覆盖数据库错误
【发布时间】:2015-03-18 21:22:05
【问题描述】:

我正在使用 mongojs 并为 mocha 编写测试,并使用 istanbul 运行覆盖率。我的问题是我想包括测试数据库错误。

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() 断开数据库并运行测试,从而导致所需的错误。当之后所有其他测试都需要数据库连接失败时,就会出现此解决方案的问题,因为我尝试重新连接但没有成功。

关于如何巧妙地解决这个问题的任何想法?最好不要编写下一个版本的mongojs 可能不会引发的自定义错误。或者有没有更好的方法来构建测试?

【问题讨论】:

    标签: node.js testing mocha.js mongojs


    【解决方案1】:

    mock 处理 mongo 的库怎么样?

    例如,假设 db.update 最终是被 collection.update 调用的函数,您可能想要执行类似的操作

    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 的独立测试间谍、存根和模拟。无依赖,适用于任何单元测试框架。

    这有意义吗?

    【讨论】:

    • 确实有道理。但是,我有点希望有一些内置的错误触发,它可以模拟一系列实际错误。在我接受这个问题作为答案之前,我会让这个问题再逗留一会儿,但感谢您的快速回复!
    • 我看到@AndreasNiedermair 编辑了我的问题,删除了对 mongojs 的引用,以及更通用的测试案例,在这种情况下,这可能不是我真正想要的。我想我的问题并不像我想象的那么普遍。
    • 我认为,如果您尝试测试错误处理,最简单的方法是模拟并将错误返回给您,但这只是恕我直言...我不知道您的情况。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    • 2016-05-04
    • 2013-07-19
    • 1970-01-01
    相关资源
    最近更新 更多