Prachi g
Prachi g

Reputation: 839

Writing test cases using Mocha and Chai

I have a following simple function:

var moment = require('moment-timezone');

exports.splitIntoDays = function(from,to) {
    var timeIntervals = [];
    var interval = {};
    var start = moment(from);
    var end = moment(to);
    if(start.isAfter(end)) {
        throw new Error('From date ('+from+') is after To date ('+to+').Enter a valid date range.');
    }
    var initial = start;
    console.log("Before loop"+initial.format("YYYY/MM/DD-HH:mm:ss")+"  "+initial.diff(end,'hours'));
    while(end.diff(initial,'hours') > 24) {
        timeIntervals.push({"from" : initial.format("YYYY/MM/DD-HH:mm:ss"), "to" : initial.add(24,'hours').format("YYYY/MM/DD-HH:mm:ss")});
        initial = initial.add(1,'hours');
    }
    timeIntervals.push({"from" : initial.format("YYYY/MM/DD-HH:mm:ss"), "to" : end.format("YYYY/MM/DD-HH:mm:ss")});
    console.info(JSON.stringify(timeIntervals));
    return timeIntervals;
}

So, if I call it, splitIntoDays('2014/09/13-10:00:00','2014/09/14-09:00:00'), I get the following response:

[ { from: '2014/09/13-10:00:00', to: '2014/09/14-09:00:00' } ]

I wrote the following test using Mocha and Chai:

var expect = require("chai").expect;
var utils = require("../Utils.js");

describe("Utils", function(){
    describe("#splitIntoDays()", function(){
        var timeIntervals = [];
        var results = utils.splitIntoDays('2014/09/13-10:00:00','2014/09/14-09:00:00');
        timeIntervals.push({ "from": '2014/09/13-10:00:00', "to": '2014/09/14-09:00:00' });
        expect(results).to.equal(timeIntervals);
    });
});

But, this one fails. Can you please help me in pointing out a mistake?

Upvotes: 1

Views: 521

Answers (1)

Louis
Louis

Reputation: 151380

You need to wrap your test in an it call and you need to use deep.equal. For instance:

it("equal", function () {
    expect(results).to.deep.equal(timeIntervals);
});

equal by itself will check that the objects are strictly equal with ===. Start Node on your computer and type [] === [] at the prompt. You'll get the result false. This is because you have two Array objects and a strict equality check will fail if the objects are not the same instance.

The it call is necessary because this is how you tell Mocha "here's a test for you to run". The describe calls declare test suites but do not themselves declare any tests.

Upvotes: 1

Related Questions