Javascript 如何对此进行模拟以继续async.each()调用

Javascript 如何对此进行模拟以继续async.each()调用,javascript,unit-testing,mongoose,promise,Javascript,Unit Testing,Mongoose,Promise,我有下面的方法,removeOldObjects,我想对其进行单元测试。它从现有对象列表中删除对象。我相信这些东西是猫鼬的例子。我理解这个方法在做什么,我正试图模拟它的输入,包括返回existinObj.remove(cb)中的remove()方法。realremove()的文档如下:(Model#remove([fn])部分)。看起来它应该还你一个承诺 我正在努力弄清楚如何有效地使返回existinObj.remove(cb)do返回cb(null)将async.each()调用移动到它的最终

我有下面的方法,
removeOldObjects
,我想对其进行单元测试。它从现有对象列表中删除对象。我相信这些东西是猫鼬的例子。我理解这个方法在做什么,我正试图模拟它的输入,包括
返回existinObj.remove(cb)
中的
remove()
方法。real
remove()
的文档如下:(Model#remove([fn])部分)。看起来它应该还你一个承诺

我正在努力弄清楚如何有效地使
返回existinObj.remove(cb)
do
返回cb(null)
async.each()
调用移动到它的最终回调,甚至该承诺应该如何完成此方法。我玩弄过使用承诺,但没有取得任何进展(最近刚学会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):


Mongoose文档
remove
方法仅在未提供回调时返回承诺。在
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] 
})
很高兴,这很有帮助,我将回答您关于摩卡咖啡的所有问题:)
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] 
})