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

标签 javascript unit-testing mongoose promise

我有以下方法 removeOldObjects 我想对其进行单元测试。它从现有对象列表中删除对象。我相信这些对象是 Mongoose 实例。我了解该方法在做什么,并且我正在尝试模拟它的输入,包括 return existinObj.remove(cb) 中的 remove() 方法。真正的 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)  
})

最佳答案

Mongoose 文档 remove 方法仅在未提供回调时返回 promise 。在 removeOldObjects 实现中提供了它。所以你不应该返回一个 promise ,而不是这个你应该调用提供的回调:

为每个existingObjects 项添加remove 函数并从这里调用回调:

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] 
})

关于javascript - 如何模拟这个以继续 async.each() 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45890486/

相关文章:

javascript - 将 Preventdefault 与将数据对象传递给函数相结合

javascript - Wordpress Gutenberg 媒体上传视频库

javascript - 我的 Virgin Parse.Query

javascript - 如何检查 Javascript 中 Unicode 字符串的相等性?

mongodb - Mongoose 选择、填充和保存在 Mac 和 Windows 上的行为不同

arrays - Mongoose 查询 : find an object by id in an array

javascript - Jstestdriver 设置和拆卸

java - 按指定顺序运行 JUnit4 测试类

python - 如何在运行单元测试时摆脱第三方库警告?

node.js - 我的 Mongoose 模式不正确吗?