Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
763 views
in Technique[技术] by (71.8m points)

node.js - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...