如何模拟这个以继续async.each()调用

时间:2017-08-25 23:19:03

标签: javascript unit-testing mongoose promise

我有以下方法,removeOldObjects我想进行单元测试。它从现有对象列表中删除对象。我相信对象是mongoose实例。我理解该方法正在做什么,我正在尝试模拟它的输入,包括remove()中的return existinObj.remove(cb)方法。真实remove()的文档位于:http://mongoosejs.com/docs/api.html(模型#remove([fn])部分)。它似乎应该返回一个Promise。

我正在努力弄清楚如何有效地让return existinObj.remove(cb)return cb(null)async.each()调用移动到其最终回调,甚至是Promise应如何完成此方法。我玩弄了Promise,但没有到达任何地方(最近只是选择了Javascript / Node)

如何定义removeMethod(在下面的脚本部分中),以便我可以正确测试此方法并达到最终回调?

方法:

const _ = require('underscore')
...
removeOldObjects (keepObjects, existingObjects, callback) {
  let objectsToReturn = []

  async.each(existingObjects, function (existinObj, cb) {
    let foundObj = _.find(keepObjects, function (thisObj) {
      return existinObj.id == thisObj.id
    })

    if (foundObj) {        
      objectsToReturn.push(object)
      return cb(null)
    } else {
      // Would like below to in effect behve like "return cb(null)",
      // so it can reach the final callback at the end
      return existinObj.remove(cb)
    }
  }, function (err) {
    return callback(err, objectsToReturn)
  })
}

测试脚本(使用Mocha):

const test = new MyClass()
const keepObjects = [{id: 5}]  // removeDeadCams() does not hit its final callback
// const keepObjects = [{id: 1}]   // removeDeadCams() runs its full course
const existingObjects = [
  {id: 1, remove: removeMethod}
]
test.removeOldObjects(keepObjects, existingObjects, function (err, res) {
  console.log('error-----')
  console.log(err)
  console.log('response-----')
  console.log(res)  
})

1 个答案:

答案 0 :(得分:1)

只有当没有提供回调时,Mongoose文档remove方法才会返回一个promise。在removeOldObjects实施中提供了它。所以你不应该返回一个承诺,而不是你应该调用提供的回调:

remove函数添加到每个existingObjects项目并从此处调用回调:

const test = new MyClass()

const oldObjects = [
  { id: 5 }
];
const existingObjects = [
  { id: 1, remove: cb => cb(1) } // call it with id of the item to validate in your test
];

test.removeOldObjects(oldObjects, existingObjects, function(err, res) {
  console.log(res); // outputs [null, 1] 
})