Integration testing with mongojs to cover database errors

≡放荡痞女 提交于 2019-12-12 06:08:45

问题


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
    });
});

the test looks like this

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.'));
    });
});

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.

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?


回答1:


What about mocking the library that deals with mongo?

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
  });

});

I've used Sinon which is

Standalone test spies, stubs and mocks for JavaScript. No dependencies, works with any unit testing framework.

Does this make sense?



来源:https://stackoverflow.com/questions/29120905/integration-testing-with-mongojs-to-cover-database-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!