繁体   English   中英

使用回调对功能进行单元测试

[英]Unit testing a function with callbacks

我在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:无法读取上下文中未定义的属性'to')

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

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

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

expect(finalOutput).to.exist

有在finalOutput对象未to.exist,这是存在于由柴返回的对象expect的功能。

话虽如此,您的测试仍将失败,因为您的错误告诉您finalOutput对象不存在(未定义)。 如果要有一个全局的finalOutput对象,则必须在代码中声明它。 您可以这样执行global.finalOutput = finalOutput (我想您是用let finalOuputconst finalOutputvar finalOutput

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM