嘲笑的对象看起来像mongoose的对象

我刚刚开始瓦/摩卡,sinon和mongoose。

我在mongoose有一个模式/模型:

var PersonSchema = new Schema({ name: { type: String, required: true }, employer: { type: Schema.Types.ObjectId, ref: 'Employer' } }); mongoose.model('Person', PersonSchema); var EmployerSchema = new Schema({ name: { type: String, required: true } }); mongoose.model('Employer', EmployerSchema); 

我有一个方法来帮助查询:

 var getPersonById = function(id, callback) { Person.findById(id, function(err, person) { if (err) return callback(err); // this really could call any mongoose function // question is if I mocked the person object is there a good // way to mock the populate method that mongoose provides person.populate('employer', function(err, populatedPerson) { return callback(err, populatedPerson); }); }); } 

我成功地嘲笑一个查询到数据库:var mockedPerson = {_id:'1',name:'test'};

 sinon.mock(PersonModel) .expects('findById') .withArgs("1") .yields(null, mockedPerson}); 

然后在我的testing中调用我的函数:

 getPersonById("1", function(err, person) { // person is: {name: 'test'}; }); 

但是我的testing失败了,因为当我嘲笑从findById调用返回的person对象时,我并没有真正的mongoose对象。 这意味着它没有填充方法。

当然我可以这样做:

 var mockedPerson = { _id: '1', name: 'test', employer: '12', populate: function() { return { name: 'test', employer: { name: 'Apple' } } } }; 

这似乎嘲笑这种方式填充方法。 我真的试图用模拟数据库调用来testinggetPersonById方法,但是我仍然想validation我正在调用填充正确的参数,也许用sinon模拟返回。

那可能吗? 我试过这样的东西,但是你不能存根不存在的方法。

 var mockedPerson = { _id: '1', name: 'test', employer: '12' }; var stub = sinon.stub(mockedPerson, 'populate') .withArgs('employer') .yields(null, { name: 'test', employer: 'apple'});