簡體   English   中英

在node.js中編寫單元測試的最佳方法是什么?

[英]What is the best way to write unit test in 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? 由於執行測試時文件將不存在。 我猜Winston記錄器也是一個有趣的部分,不確定如果將其導入到Mocha測試中是否會初始化它。 我的第一個測試顯示記錄器未定義。

最重要的單元測試原則之一是測試非常小的代碼。 為了實現這一點,您絕對應該對不屬於測試代碼的函數進行模擬或存根調用(在這種情況下為readFile和logger.error)。 對於提供的代碼,您可以制作三個測試用例:

  • 使用適當的參數調用readFile
  • 如果存在err則調用錯誤
  • 用適當的參數調用回調函數

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM