Stubbing the mongoose save method on a model Stubbing the mongoose save method on a model mongoose mongoose

Stubbing the mongoose save method on a model


Here's the final configuration I developed, which uses a combination of sinon and mockery:

// Dependenciesvar expect = require('chai').expect;var sinon = require('sinon');var mockery = require('mockery');var reloadStub = require('../../../spec/utils/reloadStub');describe('UNIT: userController.js', function() {  var reportErrorStub;  var controller;  var userModel;  before(function() {    // mock the error reporter    mockery.enable({      warnOnReplace: false,      warnOnUnregistered: false,      useCleanCache: true    });    // load controller and model    controller = require('./userController');    userModel = require('./userModel');  });  after(function() {    // disable mock after tests complete    mockery.disable();  });  describe('#createUser', function() {    var req;    var res;    var status;    var end;    var json;    // Stub `#save` for all these tests    before(function() {      sinon.stub(userModel.prototype, 'save');    });    // Stub out req and res    beforeEach(function() {      req = {        body: {          username: 'Andrew',          userID: 1        }      };      status = sinon.stub();      end = sinon.stub();      json = sinon.stub();      res = { status: status.returns({ end: end, json: json }) };    });    // Reset call count after each test    afterEach(function() {      userModel.prototype.save.reset();    });    // Restore after all tests finish    after(function() {      userModel.prototype.save.restore();    });    it('should call `User.save`', function(done) {      controller.createUser(req, res);      /**       * Since Mongoose's `new` is asynchronous, run our expectations on the       * next cycle of the event loop.       */      setTimeout(function() {        expect(userModel.prototype.save.callCount).to.equal(1);        done();      }, 0);    });  }}


Have you tried:

sinon.stub(userModel.prototype, 'save')

Also, where is the helper function getting called in the test? It looks like you define the function as the utils module, but call it as a method of a controller object. I'm assuming this has nothing to do with that error message, but it did make it harder to figure out when and where the stub was getting called.