1

I have written the following test case in Mocha, where the my code uses Q module.

var expect = require("chai").expect;
var utils = require("../Utils.js");
var utils1 = require("../a.js");
var sinon = require('sinon');
var request = require('requestretry');
var querySys = require('../b.js');
var Q = require("q");

describe("Sample", function () {
    var results;
    describe("#get()", function () {
        before(function (done) {
            done();
        });
        it("equal", function () {
            var deferred = Q.defer();
            var responseData = {};
            responseData.code = 200;
            responseData.data = [{a:1,b:2}];
            deferred.resolve(responseData);
            //querySys1 method uses Q promises. That is how I stubbed the response.
            sinon.stub(querySys, 'querySys1').returns(deferred.promise);

            //get function internally calls querySys1. Hence I have stubbed that.
            results = utils1.get(specification);
            results.then(function (data) {
                //Here I do see data coming as {in:1, out:1}. But still the test case is passing when compare it with {}.
                console.log(data);
                //Ideally, it should have failed. But it is passing.
                expect(data).to.be.equal({});
            });
        });
        after(function (done) {
            done();
        })
    });
});

So, if you see, I am trying to do assertion check in results.then part. I have printed the response, which I am receiving. That is coming as expected. But I am intentionally trying to match with wrong value, but test case is still passing.

Prachi g
  • 849
  • 3
  • 9
  • 23

2 Answers2

0

Since your test does not include a callback, execution runs through the main block and declares the test as passing without waiting for the result of the then function. You need to let mocha know to wait for the callback:

it("equal", function (done) {
    ...
    results.then(function (data) {
        console.log(data);
        expect(data).to.be.equal({});
        return done();
    });
});
Jorge Aranda
  • 2,050
  • 2
  • 20
  • 29
  • Now it is throwing the following error: `Error: timeout of 2000ms exceeded`. But even though I get the result in less time. Because `console.log(data)` print the output very quickly. – Prachi g Jan 22 '15 at 07:10
0

When I changed results.then to results.done, test started failing as expected. Can someone say whether this is the right approach.

Prachi g
  • 849
  • 3
  • 9
  • 23