-1

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?

Nextor
  • 95
  • 1
  • 1
  • 7

1 Answers1

1

You can use Chai Assertions for Promises. This package extends Chai with a fluent language for asserting facts about promises.

You can write code that expresses what you really mean:

return doSomethingAsync().should.eventually.equal("foo");

See more here: https://www.chaijs.com/plugins/chai-as-promised/

If you don't want to turn your functions into promises, you'll need to test your code in this manner

it("Using setTimeout to simulate asynchronous code!", function(done){
    setTimeout(function() {
        done();
    }, 3000);
});
Gabriel Vasile
  • 2,110
  • 1
  • 14
  • 26
  • That's great! Would it work for code that uses `setTimeout`, though? – Yves Gurcan Dec 21 '19 at 19:21
  • That would test an asynchronous function that returns a Promise, which is not the case for the method I want to test in my example. – Nextor Dec 21 '19 at 20:44
  • Thanx for your answers but, once again, that is not what I am trying to test in my example. As I say in my question, I need to test the method "calculate" from my example, which doesn't take any callbacks. I need to test the values of the member "result" depending on the parameters passed to "calculate". – Nextor Dec 22 '19 at 03:04