JohanObrink / mongoose-mock

MIT License
34 stars 23 forks source link

Models are stored and can be retrieved by name. #1

Closed sebmartel closed 10 years ago

sebmartel commented 10 years ago

Here is a patch that allows for #model() to store Models by name. It is typical to use mongoose this way:

model.js

var mongoose = require('mongoose');

var MyModel = new mongoose.Schema();
mongoose.model('MyModel', MyModel); // no exports

controller.js

var mongoose = require('mongoose')
  , MyModel = mongoose.model('MyModel');

exports.create = function(req, res, next) {
  var newItem = new MyModel(...);
}

test.js

var mmock = require('mongoose-mock')
  , proxyquire = require('proxyquire')
  , chai = require('chai')
  , sinon = require('sinon')
  , sinonChai = require('sinon-chai')
  ;

describe('controller test', function() {
  var controller
    , modelStub;

  before( function() {
    proxyquire('model.js', { 'mongoose': mmock });
    modelStub = mongooseMock.model('MyModel');  // needs to return model created by
                                                // the above proxyquire.
    modelStub.... // add spies

    // time to load the controller.
    controller = proxyquire('controller.js',  { 'mongoose': mmock });  // our stub model is loaded.
  });

  it( 'creates models', function() {
    controller.create()
    expect( modelStub )...
  });
});

For another real use-case, this is how the mean.io sets up their framework with mongoose.

Code and test in pull request. Cheers

JohanObrink commented 10 years ago

Thans for the commits!

I merged them and bumped to a new minor version since there is new functionality in there :)