jeudi 7 juillet 2016

How to mock a mongoose model inside a function I want to unit test?

I have a library which handle all calls to the DB, I wanted to completely abstract the DB from my app since I may have to use something else than mongoDB.

As such, I don't want to mock mongoose inside my unit test, as proposed by sinon-mongoose, mongoose-mock, but inject the mock inside the file.

I presumed there is a way to use proxyquire to inject a mock mongoose, and stub .model() so it can return a mock model, but I can't find any example of how that would be done.

var mongoose = require('mongoose'); //proxyquire this

var db = {},
    Doc = {};

function connect(callback) {
    db = mongoose.createConnection('mongodb://127.0.0.1/db');
    db.on('error', (err) => {
        callback(err);
    });
    db.once('open', function () {
        Doc = mongoose.model('Doc', mongoose.Schema({ //So that I can inject a mock Doc model
            date: Date,
            data: String
        }));
        callback();
    }); 
}

function save(data, callback) {
    new Doc(data).save((err) => { //So I can make save throw or not a error.
        callback(err);
    });
}

module.exports = {
    connect: connect,
    save: save
}

Aucun commentaire:

Enregistrer un commentaire