Unit testing read file with Promise and nodeunit

This post will demonstrate a sample usage of using unit testing framework nodeunit to test a Promise function for reading file content.

1. Install nodeunit if you don’t have it installed yet.

npm install nodeunit -g

2. Create a project folder my_project and a test folder inside it

mkdir my_project
mkdir my_project/test

3. Create my_project/filereader.js with the following code

var fs = require('fs');
exports.readFile = function (filePath) {
	if (!filePath) throw "file path is required";
	return new Promise((resolve, reject) => {
		fs.readFile(filePath, 'utf8', (err, data) => {
		  if (err) throw err;
		  resolve(data);
		});			
	});
}

4. Create the test file for testing the filereader, my_project/test/test_filereader.js with the following content.

var fs = require('fs');
var fileReader = require('../filereader');
var testFilePath = __dirname + "/../a_file_with_some_content.txt";

module.exports = {
    setUp: function (cb) {
        console.log("setUp");
        return cb();
    },
    tearDown: function (cb) {
        console.log("tearDown");
        return cb();
    },
    'test read file': function(test) {
        test.expect(2);
        test.throws(() => {fileReader.readFile();});

        testFileContent = fs.readFileSync(testFilePath, "utf8");
        fileReader.readFile(testFilePath)
        .then((content) => {
            test.equal(content, testFileContent);
            test.done();
        })
        .catch(console.log);
    },
    "another dummy test": function(test) {
        test.equal(1,1);
        test.done();
    }
};

5. Create my_project/a_file_with_some_content.txt with some content it, any content would work.

6. Run the test from the command line in the my_project folder

nodeunit test

Search within Codexpedia

Custom Search

Search the entire web

Custom Search