I would like to stub the save method available to Mongoose models. Here's a sample model:
var mongoose = require('mongoose'); var userSchema = mongoose.Schema({ username: { type: String, required: true } }); var User = mongoose.model('User', userSchema); module.exports = User;
I have a helper function that will call the save method.
var User = require('./model'); module.exports = function(req, res) { var username = req.body.username; var user = new User({ username: username }); user.save(function(err) { if (err) return res.end(); return res.sendStatus(201); }); };
I would like to verify that user.save is called inside my helper function using unit test.
var mongoose = require('mongoose'); var createUser = require('./utils'); var userModel = require('./model'); it('should do what...', function(done) { var req = { username: 'Andrew' }; var res = { sendStatus: sinon.stub() }; var saveStub = sinon.stub(mongoose.Model.prototype, 'save'); saveStub.yields(null); createUser(req, res);
I found var saveStub = sinon.stub(mongoose.Model.prototype, 'save') from here .
Everything is fine, unless I try to add something to my saveStub , for example. with saveStub.yields(null) . If I wanted to simulate the error passed to the save return message with saveStub.yields('mock error') , I get this error:
TypeError: Attempted to wrap undefined property undefined as function
Stack tracing is completely useless.
Study i did
I tried to reorganize my model to gain access to the user's base model, as recommended here . This gave me the same error. Here is my code for this attempt:
var UserSchema = mongoose.model('User'); User._model = new UserSchema(); var saveStub = sinon.stub(userModel._model, 'save');
I found that this solution does not work for me at all. Maybe this is because I'm setting up my user model differently?
I also tried Mockery after this guide and this one , but it was much more complicated than I thought it was necessary, and made me question the value of wasting time to isolate db.
I got the impression that all this has to do with the mysterious way mongoose implements save . I read something about this using npm hooks , which makes the save method a slippery thing to stub.
I also heard about mockgoose , although I have not tried this solution yet. Has anyone succeeded in this strategy? [EDIT: it turns out that mockgoose provides a database in memory for ease of setup / stall, but this does not solve the problem of trimming.]
Any understanding of how to solve this problem would be greatly appreciated.