actor203
actor203

Reputation: 176

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.

Upvotes: 6

Views: 1615

Answers (2)

David da Silva
David da Silva

Reputation: 73

Since you are using a Promise, I suggest to simply return it at the end of the it. Once the Promise is settled (fulfilled or rejected), Mocha will consider the test done and it will consume the Promise. In case of a rejected Promise, it will use its value as the thrown Error.

NB: do not declare a done argument if you are returning a Promise.

Upvotes: 3

alexmac
alexmac

Reputation: 19587

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

Upvotes: 4

Related Questions