Tuesday, 30 May 2017

What is the right way to unit test asynchronous functions in NodeJS using Mocha?

I need an extremely simple example on how to test function like this:

// Read from Redis DB
Main.prototype.readFromRedis = function(key, callback){
    dbClient.get(key, function(err, reply) {
        return callback(err, reply)
    });
}

or this:

// Write to file
Main.prototype.writeToFile = function(fileName, content, callback){
    fs.appendFile(fileName, content, encoding='utf8', function (err) {
        return callback(err);
    });
}

I've been searching for the optimal solution for quite a while but wasn't able to find anything very useful.

My attempts:

describe('main', function() {
  it('readFromRedis(key, callback) should read value from DB', function() {
    var main = new Main();
    var error;
    main.readFromRedis('count',function(err){
        err = error;
        });
    expect(error).to.equal(undefined);
  });
});

However here the expect() executes before the readFromRedis besides that I don't find my solution to be the right one.



via Ondrej Tokar

No comments:

Post a Comment