lundi 21 décembre 2015

How to test a recursively called function in NodeJS?

I have a recurring function written in ES6/7 which is transpiled by babel. I have a recurring function created that checks if there is a user document, using mongoose.

// 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
  }
}

If there is no user I am using the delay library to delay execution for a minute upon which the function is called recursively.

This allows the halting of execution of the overall function until a user is found:

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

The else branch is very easy to generate tests for. How do I create a test for the if branch that verifies the recursion is working properly?

At the moment I have replaced the delay method with proxyquire during testing, subbing it for a custom delay function that just returns a value. At that point I can change the code to look like this:

// 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 
  }
}

Issue there is that the source code is being changed to accommodate for the test. Is there a better, cleaner solution?

Aucun commentaire:

Enregistrer un commentaire