我有一个用ES6 / 7编写的循环函数,该函数由babel编译。我创建了一个循环功能,使用猫鼬检查是否有用户文档。

// Keep checking if there is a user, if there is let execution continue
export async function checkIfUserExists(){
  let user = await User.findOneAsync({});
  // if there is no user delay one minute and check again
  if(user === null){
    await delay(1000 * 60 * 1)
    return checkIfUserExists()
  } else {
    // otherwise, if there a user, let the execution move on
    return true
  }
}


如果没有用户,我将使用delay库将执行延迟一分钟,然后递归调用该函数。

这允许在发现用户之前停止执行整体功能:

async function overallFunction(){
  await checkIfUserExists()
  // more logic
}


else分支非常易于生成测试。如何为if分支创建测试以验证递归是否正常工作?

目前,在测试过程中,我已使用proxyquire替换了delay方法,将其替换为一个仅返回值的自定义延迟函数。到那时,我可以将代码更改为如下所示:

// Keep checking if there is a user, if there is let execution continue
export async function checkIfUserExists(){
  let user = await User.findOneAsync({});
  // if there is no user delay one minute and check again
  if(user === null){
    let testing = await delay(1000 * 60 * 1)
    if (testing) return false
    return checkIfUserExists()
  } else {
    // otherwise, if there a user, let the execution move on
    return
  }
}


问题在于,正在更改源代码以适应测试。有更好,更清洁的解决方案吗?

最佳答案

我不确定您为什么要使用递归解决方案而不是迭代解决方案-但是如果没有其他原因,那么迭代编写它可能会更容易,因为您不会因此而感到烦恼:

  do{
  let user = await User.findOneAsync({});
  // if there is no user delay one minute and check again
  if(user === null){
    await delay(1000 * 60 * 1);
  }
  else{
    return true;
  }
  }while (!user);


尚未通过解释程序进行测试或运行-但是您知道了。

然后在您的测试模式下-仅提供一个测试用户。因为您可能仍然需要编写使用对用户的引用的测试。

关于javascript - 如何在NodeJS中测试递归调用的函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34404766/

10-11 22:22
查看更多