2016-05-13 69 views
0

我有一個模塊,我加載鬍子模板文件。我想寫一個單元測試。我正嘗試使用摩卡,柴和rewire。在node.js中編寫單元測試的最佳方法是什麼?

這裏是我的module.js:

var winston = require('winston'); 
var fs = require('fs'); 
var config = require('./config.js'); 
exports.logger = new winston.Logger({ 
    transports: [ 
     new winston.transports.File(config.logger_config.file_transport), 
     new winston.transports.Console(config.logger_config.console_transport) 
    ], 
    exitOnError: false 
}); 
exports.readTemplateFile = function(templateFile, callback) { 
     fs.readFile(config.base_directory + templateFile + '.tpl.xml', 'utf8', function (err, data) { 
      if (err) { 
       logger.error('Could not read template ' + templateFile + ': ' + err); 
      } 
      callback(data); 
     }); 
    }; 

在我用鬍子做模板的東西回調函數。 什麼是測試這個最好的方法?

也許我將不得不重新鏈接fs.readFile?由於在執行測試時文件不在那裏。溫斯頓記錄器也是一個我感興趣的部分,我不確定它是否會被初始化,如果我在摩卡測試中導入它。我的第一個測試顯示記錄器是未定義的。

回答

3

最重要的單元測試原理之一是測試非常小的一段代碼。爲了達到這個目的,你應該把模塊或存根調用到不屬於測試代碼的函數(在這種情況下是readFile和logger.error)。對於提供的代碼就可以使三個測試用例:

  • 調用READFILE用正確的參數
  • 調用錯誤,如果犯錯存在
  • 調用回調函數與正確的參數

您的回調函數應該是在此代碼之外進行測試,例如通過提供假數據作爲參數:

define('Some test',() => { 
    it('should return true',() => { 
    expect(callbackFunction('fakeData').to.be.ok); 
    }); 
}); 
相關問題