用Sinon对Mongoose模型进行挖掘

时间:2012-07-03 20:50:46

标签: node.js mongoose sinon

我想在特定模型中为Mongoose save方法创建一个存根,以便我创建的模型的任何实例都将调用存根而不是普通的Mongoose save方法。我的理解是,这样做的唯一方法是将整个模型存根如下:

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

不幸的是,这行代码导致我的测试抛出以下错误:

TypeError: Cannot read property 'states' of undefined

有谁知道这里出了什么问题?

6 个答案:

答案 0 :(得分:25)

有两种方法可以实现这一目标。第一个是

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

如果您控制log mongoose.Model,您将看到模型可用的方法(特别是这不包括lte选项)。

另一种(特定型号)方式是

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

同样,存根可以使用相同的方法。

编辑:某些方法如保存存根如下:

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

答案 1 :(得分:5)

看看sinon-mongoose。您可以只用几行来预测链式方法:

sinon.mock(YourModel).expects('find')
  .chain('limit').withArgs(10)
  .chain('exec');

您可以在回购中找到工作示例。

另外,建议:使用mock方法代替stub,这将检查方法是否真的存在。

答案 2 :(得分:4)

save不是模型上的方法,它是文档上的方法(模型的实例)。陈述here in mongoose docs

  

构建文件

     

文档是我们模型的实例。创建它们并保存到数据库很容易

因此,如果您使用模型模拟save()

,则始终未定义

使用sinon-mongoose&和@ Gon的回答。 factory-girl Account是我的模特:

无效

var AccountMock = sinon.mock(Account)

AccountMock
  .expects('save') // TypeError: Attempted to wrap undefined property save as function
  .resolves(account)

工作

var account = { email: 'sasha@gmail.com', password: 'abc123' }

Factory.define(account, Account)
Factory.build('account', account).then(accountDocument => {
  account = accountDocument

  var accountMock = sinon.mock(account)

  accountMock
    .expects('save')
    .resolves(account)

  // do your testing...
})

答案 3 :(得分:1)

而不是整个对象,请尝试:

sinon.stub(YOURMODEL.prototype, 'save')

确保YOURMODEL不是实例的类。

答案 4 :(得分:0)

与切线相关,但相关...

我需要模拟一个自定义模型方法,例如:

myModelSchema.methods.myCustomMethod = function() {....}

我创建了一个存根:

myCustomMethodStub = sinon.stub(MyModel.schema.methods, 'myCustomMethod').callThrough();

答案 5 :(得分:0)

如djv所述,save方法在文档上。因此,您可以通过以下方式存根:

const user = new User({
      email: 'email@email.com',
      firstName: 'firstName',
      lastName: 'lastName',
      userName: 'userName',
      password: 'password',
    });

stub(user, 'save').resolves({ foo: 'bar' });

奖金,您可以通过ChaiChai as promised这样声明:

const promise = user.save();
await chai.assert.doesNotBecome(promise, { foo: 'bar' });
相关问题