Search code examples
javascriptnode.jsmocha.jsbddassert

mocha js assertion hangs while using promise?


"use strict";
let assert = require("assert");

describe("Promise test", function() {
  it('should pass', function(done) {
    var a = {};
    var b = {};
    a.key = 124;
    b.key = 567;
    let p = new Promise(function(resolve, reject) {
        setTimeout(function() {
            resolve();
        }, 100)
    });

    p.then(function success() {

        console.log("success---->", a, b);
        assert.deepEqual(a, b, "response doesnot match");
        done();
    }, function error() {

        console.log("error---->", a, b);
        assert.deepEqual(a, b, "response doesnot match");
        done();
    });
 });
});

Output: output result

I am using node v5.6.0. The test seems to hang for assert when values don't match.

I tried to check if it's issue with assert.deepEqual using setTimeout but it works fine.

But it fails while using Promise and hangs if the values don't match.


Solution

  • You're getting that error, because your test is never finished. This assertion: assert.deepEqual(a, b, "response doesnot match"); throws an error, and so as you haven't catch block, done callback is never called.

    You should add catch block in the end of promise chain:

    ...
    p.then(function success() {
        console.log("success---->", a, b);
        assert.deepEqual(a, b, "response doesnot match");
        done();
    }, function error() {
        console.log("error---->", a, b);
        assert.deepEqual(a, b, "response doesnot match");
        done();
    })
    .catch(done); // <= it will be called if some of the asserts are failed