[英]Unit testing a function with callbacks
I have a function in node.js: 我在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');
});
}
});
})
})
});
I would like to write tests on the 'finalOutput' variable, the content of the files (for example, if a file is empty the output should be X, and so on), and the existence of output files. 我想对'finalOutput'变量,文件的内容(例如,如果文件为空,则输出应为X等)以及输出文件的存在进行测试。 But when I run npm test (I am using mocha and chai, I get ' TypeError: Cannot read property 'to' of undefined at Context')
但是,当我运行npm test(我正在使用mocha和chai时,出现'TypeError:无法读取上下文中未定义的属性'to')
This is an example of a test I want to run: 这是我要运行的测试的示例:
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
There isn't to.exist in the finalOutput object, this is present in the object returned by chai's expect
function. 有在finalOutput对象未to.exist,这是存在于由柴返回的对象
expect
的功能。
That being said, your test will still fail since your error is telling you that the finalOutput
object doesn't exist(is undefined). 话虽如此,您的测试仍将失败,因为您的错误告诉您
finalOutput
对象不存在(未定义)。 If you want there to be a global finalOutput
object then you must declare it inside your code. 如果要有一个全局的
finalOutput
对象,则必须在代码中声明它。 You may do it like this global.finalOutput = finalOutput
(I guess you declared it with let finalOuput
or const finalOutput
or var finalOutput
) 您可以这样执行
global.finalOutput = finalOutput
(我想您是用let finalOuput
或const finalOutput
或var finalOutput
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.