Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stubbing a Mongoose model with Sinon

I want to create a stub for the Mongoose save method in a particular model, so that any instance of my model I create will call the stub instead of the normal Mongoose save method. My understanding is that the only way to do this is to stub the entire model like this:

var stub = sinon.stub(myModel.prototype); 

Unfortunately, this line of code causes my tests to throw the following error:

TypeError: Cannot read property 'states' of undefined 

Does anyone know what is going wrong here?

like image 636
amandawulf Avatar asked Jul 03 '12 20:07

amandawulf


People also ask

How do I stub an object in Sinon?

If you need to check that a certain value is set before a function is called, you can use the third parameter of stub to insert an assertion into the stub: var object = { }; var expectedValue = 'something'; var func = sinon. stub(example, 'func', function() { assert. equal(object.

How does Sinon stub work?

The sinon. stub() substitutes the real function and returns a stub object that you can configure using methods like callsFake() . Stubs also have a callCount property that tells you how many times the stub was called. For example, the below code stubs out axios.

What is stubbing in JavaScript?

What are Stubs? A test stub is a function or object that replaces the actual behavior of a module with a fixed response. The stub can only return the fixed response it was programmed to return.

What is the difference between a mongoose Schema and model?

Mongoose Schema vs. Model. A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.


1 Answers

There are two ways to accomplish this. The first is

var mongoose = require('mongoose'); var myStub = sinon.stub(mongoose.Model, METHODNAME); 

If you console log mongoose.Model you will see the methods available to the model (notably this does not include lte option).

The other (model specific) way is

var myStub = sinon.stub(YOURMODEL.prototype.base.Model, 'METHODNAME'); 

Again, the same methods are available to stub.

EDIT: Some methods such as save are stubbed as follows:

var myStub = sinon.stub(mongoose.Model.prototype, METHODNAME); var myStub = sinon.stub(YOURMODEL.prototype, METHODNAME); 
like image 158
Jacob Avatar answered Sep 18 '22 18:09

Jacob