0

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.

Ondrej Tokar
  • 4,898
  • 8
  • 53
  • 103
  • 1
    Have you seen the [async code](https://mochajs.org/#asynchronous-code) section in the mocha docs? You can use `done` in this scenario. – dan May 30 '17 at 12:05

1 Answers1

1

Mocha has support for aync functions (docs). You can use done to signal the end of the test. Like this:

describe('main', function() {
  // accept done as a parameter in the it callback
  it('readFromRedis(key, callback) should read value from DB', function(done) {
    var main = new Main();
    main.readFromRedis('count',function(err){
        expect(error).to.equal(undefined);
        // call done() when the async function has finished
        done()
    });
  });
});

When you pass done as a parameter into the it callback, then the test won't complete until done has ben called, or the timeout has been reached.

dan
  • 1,944
  • 1
  • 15
  • 22