Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including mongoose-mock with all npm packages installed. Try it out:

var mongooseMock = require("mongoose-mock")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

mongoose-mock v0.4.0

A replacement for mongoose in tests returning models with sinon stubs for methods

mongoose-mock

Build Status

Installation

  npm install mongoose-mock

Usage

mongoose-mock is used for swapping out mongoose in unit tests. Use something like proxyquire to change the dependency.

model/User.js

var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

var User = new Schema({});
User.statics.createAndSave = function (props, callback) {
  var user = new User(props);
  user.save(function(err, result) {
    callback(err, result);
  });
  return user;
};

module.exports = mongoose.model('User', User);

test/unit/model/User.js

var mongooseMock = require('mongoose-mock'),
  proxyquire = require('proxyquire'),
  chai = require('chai'),
  expect = chai.expect,
  sinon = require('sinon'),
  sinonChai = require("sinon-chai");
chai.use(sinonChai);

describe('User', function () {

  var User;

  beforeEach(function () {
    User = proxyquire('../../../model/User', { 'mongoose': mongooseMock });
  });

  describe('.createAndSave', function () {
    it('saves the user', function () {
      var callback = sinon.spy();
      var user = User.createAndSave({ title: 'Mr', lastName: 'White' }, callback);
      expect(user.save).calledOnce;
    });
  });
});
RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free