使用回调单元测试函数

时间:2018-02-25 12:16:23

标签: javascript node.js mocha chai

我在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测试时(我正在使用mocha和chai,我得到' TypeError:无法读取属性'未定义在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);
});
});

1 个答案:

答案 0 :(得分:0)

expect(finalOutput).to.exist

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

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