使用Mocha在NODEJ中测试单位异步功能的正确方法是什么?



我需要一个非常简单的示例,涉及如何测试功能:

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

或以下:

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

我已经搜索了一段时间的最佳解决方案,但找不到任何非常有用的东西。

我的尝试:

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);
  });
});

但是,在这里,expect()readFromRedis之前执行,此外,我没有找到我的解决方案是正确的。

摩卡咖啡具有对Aync函数(DOC(的支持。您可以使用done来发出测试结束的信号。这样:

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()
    });
  });
});

当您将done作为参数传递到it回调时,在done打电话或已达到超时之前,测试才能完成。

相关内容

最新更新