【问题标题】:Unit testing a function with callbacks使用回调对函数进行单元测试
【发布时间】:2018-02-25 12:16:22
【问题描述】:

我在 node.js 中有一个函数:

fs.readdir(filesPath, function(err, items) {

    items.forEach(function(filename){


        fs.readFile(path.join(filesPath,filename), {encoding: 'utf-8'}, function (err,data){

        //do some calculations with data from each file, the result is an object 'finalOutput'


    fs.stat(path.join(__dirname,'output.csv'), function (err, stat) {
        //check if file exists

            fs.appendFile(path.join(__dirname,'output.csv'), csv, function (err) {
            // append output to csv 
    });
}
        else {
            //create file

            fs.writeFile(path.join(__dirname,'output.csv'), fields, function (err, stat) {
            if (err) console.log(err);
            console.log('File saved');
    });
}
});



   })
  })
});

我想对 'finalOutput' 变量、文件内容(例如,如果文件为空,则输出应为 X 等)以及输出文件的存在编写测试。但是当我运行 npm test 时(我正在使用 mocha 和 chai,我得到' TypeError: Cannot read property 'to' of undefined at Context')

这是我要运行的测试示例:

var chai = require('chai'),
expect = chai.expect,
mypreviouscode = require('./mypreviouscode');

describe('test1', function() {
it('There output should always exist', function() {
expect(finalOutput.to.exist);
});
});

【问题讨论】:

    标签: javascript node.js mocha.js chai


    【解决方案1】:

    expect(finalOutput).to.exist

    finalOutput 对象中没有 to.exist,它存在于 chai 的 expect 函数返回的对象中。

    话虽如此,您的测试仍然会失败,因为您的错误告诉您finalOutput 对象不存在(未定义)。如果您希望有一个全局 finalOutput 对象,那么您必须在代码中声明它。你可以这样做global.finalOutput = finalOutput(我猜你是用let finalOuputconst finalOutputvar finalOutput声明的)

    【讨论】:

    • 我现在已经将它声明为一个全局的,但它仍然是未定义的。当我执行该功能时它工作正常,但在测试期间却不行。是不是因为函数正在异步读取文件?
    • 是的,显然。在测试中运行 expect 之前,您应该有办法等待所有异步内容完成执行。如果我没记错的话,如果你返回一个承诺,摩卡咖啡会等待it('description', function(){ return new Promise((resolve, reject) => {setTimeout(() => expect(...), 2000)})})
    猜你喜欢
    • 2021-10-23
    • 1970-01-01
    • 2014-02-28
    • 2018-08-29
    • 2019-05-16
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    • 2013-05-22
    相关资源
    最近更新 更多