I am relatively new at Node.js. Now I am writing my unit test with Mocha and Chai and found myself stuck when it comes to test the code inside anonymous functions that are written as callbacks for async functions.
I recreated some example code to explain my situation. Having these async functions:
asyncAddition = function (a, b, callback) {
setTimeout(() => {
callback(a + b);
}, 3000);
}
asyncSubstraction = function (a, b, callback){
setTimeout(() => {
callback(a - b);
}, 3000);
}
I want to use them in a class method calculate
that does not take any callback as a parameter, but just two operands a
and b
and a string with the type of the calculation, which is made asynchronously and puts the outcome in the result
member:
class Example{
constructor(){
this.result = null;
}
calculate(a, b, action){
if (action == "add") {
asyncAddition(a, b, (result) =>{
this.result = result;
console.log("Addition result is: " + result);
});
}
else if (action == "substract") {
asyncSubstraction(a, b, (result) =>{
this.result = result;
console.log("Substraction result is: " + result);
});
}
}
}
Since the value in result
is set inside the callback code, how can I write a proper test for the calculate
method that checks the values of result
depending on the given parameters?