Z T
Z T

Reputation: 570

What is the best way to write unit test in node.js?

I have a module where I load a mustache template file. I would like to write a unit test for this. I am trying to use mocha, chai and rewire.

Here is my module.js:

var winston = require('winston');
var fs = require('fs');
var config = require('./config.js');
exports.logger = new winston.Logger({
    transports: [
        new winston.transports.File(config.logger_config.file_transport),
        new winston.transports.Console(config.logger_config.console_transport)
    ],
    exitOnError: false
});
exports.readTemplateFile = function(templateFile, callback) {
        fs.readFile(config.base_directory + templateFile + '.tpl.xml', 'utf8', function (err, data) {
            if (err) {
                logger.error('Could not read template ' + templateFile + ': ' + err);
            }
            callback(data);
        });
    };

In the callback function I use mustache to do something with the template. What is the best way to test this?

Maybe I will have to rewire the fs.readFile? As the file won't be there when the test will be executed. The Winston logger is also an interesting part I guess, not sure if it will be initialized if I import this within a mocha test. My first test shows the logger is undefined.

Upvotes: 0

Views: 391

Answers (1)

Adrian Rutkowski
Adrian Rutkowski

Reputation: 309

One of the most important unit testing principle is testing very small piece of code. To achieve that you should definitely mock or stub calls to functions that not belong to testing code (readFile and logger.error in this case). For provided code you can make three test cases:

  • calling readFile with proper arguments
  • calling error if err is present
  • calling callback function with proper argument

Your callback function should be tested outside this code, for e.g. by providing fake data as parameter:

define('Some test', () => {
    it('should return true', () => {
    expect(callbackFunction('fakeData').to.be.ok);
  });
});

Upvotes: 3

Related Questions