简体   繁体   中英

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. If I use a stub it says that the .sort is a property and cannot be used as a function. 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.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 (){}[,...])". Does anybody know what function (){}[,...] means as compared to 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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