简体   繁体   English

单元测试用Sinon进行Mongoose模型回调

[英]Unit Testing Mongoose Model Callback with Sinon

I have code that looks like this: 我的代码看起来像这样:

function dummy (options, callback) {
  MModel.find({x: options.y},
  function (err, res) {
    if (err) {
      return callback(err);
    }
    if (res) {
      callback(null, res.sort({timestamp : 1}));
    } else {
      callback(null, {});
    }
  }).sort({timestamp : -1}).limit(5);
}

I am attempting to unit test this function however I cannot stub the function MModel.find because it has a res.sort within it and a .sort followed by a .limit outside. 我试图对这个函数进行单元测试,但是我不能将函数MModel.find存根,因为它有一个res.sort,一个.sort后跟一个.limit。 If I use a stub it says that the .sort is a property and cannot be used as a function. 如果我使用存根,则表示.sort是一个属性,不能用作函数。 The next thing I tried was mocking the model itself using sinon-mongoose, however, I was running into the issue that exec is not a function since I was following the sinon-mongoose documentation: 我尝试的下一件事是使用sinon-mongoose模拟模型本身,但是,我遇到了exec不是函数的问题,因为我遵循了sinon-mongoose文档:

sinon.mock(MongooseModel)
  .expects('find')
  .chain('limit').withArgs(10)
  .chain('sort').withArgs('-date')
  .chain('exec')
  .yields(null, 'SOME_VALUE');

I added the done callback and played around with adding the done callback to expects('find').withArgs({ x: 'abc' }, done) and it was giving me an expectation error that said "unexpected function find({ x:'abc'}, function (){}) when expected function is find({ x:'abc'}, function (){}[,...])". 我添加了完成回调并且使用完成回调添加到期望('find')。withArgs({x:'abc'},完成)并且它给了我一个期望错误,表示“意外函数发现({x :'abc'},function(){})当找到预期的函数时({x:'abc'},function(){} [,...])“。 Does anybody know what function (){}[,...] means as compared to function (){}? 有没有人知道function(){} [,...]与function(){}相比意味着什么?

Any help is appreciated. 任何帮助表示赞赏。 Thanks! 谢谢!

Figured it out issue was me passing the done callback that was not the right way to go about it. 弄清楚问题是我通过了完成回调,这不是正确的方法。 The actual issue dealt with using regular callbacks over exec callbacks. 实际问题涉及对exec回调使用常规回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM