2017-05-30 37 views
0

我需要如何測試功能這樣一個非常簡單的例子:使用Mocha在NodeJS中對異步函數進行單元測試的正確方法是什麼?

// 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除此之外我不覺得我的解決方案是合適的人之前執行。

+1

你見過mocha文檔中的[async code](https://mochajs.org/#asynchronous-code)部分嗎?你可以在這種情況下使用'done'。 – dan

回答

1

摩卡支持異步功能(docs)。您可以使用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有本叫,或timeout已經達到。

相關問題