【问题标题】:What is the best way to write unit test in node.js?在 node.js 中编写单元测试的最佳方法是什么?
【发布时间】:2016-05-13 18:13:35
【问题描述】:

我有一个模块,我在其中加载了一个 mustache 模板文件。我想为此编写一个单元测试。我正在尝试使用 mocha、chai 和 rewire。

这是我的 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);
        });
    };

在回调函数中,我使用 mustache 对模板进行处理。 对此进行测试的最佳方法是什么?

也许我必须重新连接 fs.readFile?因为执行测试时文件不存在。我猜 Winston 记录器也是一个有趣的部分,如果我在 mocha 测试中导入它,不确定它是否会被初始化。我的第一个测试显示记录器未定义。

【问题讨论】:

    标签: javascript node.js unit-testing mocha.js chai


    【解决方案1】:

    最重要的单元测试原则之一是测试非常小的代码。为了实现这一点,您绝对应该模拟或存根调用不属于测试代码的函数(在这种情况下为 readFile 和 logger.error)。对于提供的代码,您可以制作三个测试用例:

    • 使用适当的参数调用 readFile
    • 如果出现错误则调用错误
    • 使用正确的参数调用回调函数

    您的回调函数应在此代码之外进行测试,例如通过提供虚假数据作为参数:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-03
      • 2020-11-19
      • 1970-01-01
      • 2010-09-08
      • 2023-03-10
      • 2012-05-22
      相关资源
      最近更新 更多