Stubbing the mongoose save method on a model

前端 未结 2 910
太阳男子
太阳男子 2020-12-17 18:58

I would like to stub the save method available to Mongoose models. Here\'s a sample model:

/* model.js */
var mongoose = require(\'mongoose\');
         


        
相关标签:
2条回答
  • 2020-12-17 19:17

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

    // Dependencies
    var 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);
        });
      }
    }
    
    0 讨论(0)
  • 2020-12-17 19:23

    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.

    0 讨论(0)
提交回复
热议问题