简体   繁体   中英

Unit testing a function with callbacks

I have a function in 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. But when I run npm test (I am using mocha and chai, I get ' TypeError: Cannot read property 'to' of undefined at Context')

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.

That being said, your test will still fail since your error is telling you that the finalOutput object doesn't exist(is undefined). If you want there to be a global finalOutput object then you must declare it inside your code. You may do it like this global.finalOutput = finalOutput (I guess you declared it with let finalOuput or const finalOutput or var finalOutput )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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