Gopesh
Gopesh

Reputation: 3950

Mocha before executes after It block

I am trying to do unit test case for node.js using mocha and chai.

index.js

module.exports = {
    setA: function () {
        return new Promise(function () {
            setTimeout(function () {
                console.log("aaaa");
                a = 1;
            }, 2000)

        })
    }
}

index.spec.js

var assert = require("assert");
var SetA = require("./index")
a = 0;
before(function() {
  SetA.setA();

});
it('a should be set to 1', function() {
  assert(a === 1);
});
A promise is returned from the SetA method in index.js file. before block is not waiting to be completed. After 2000 milliseconds only the before block is completed.so my test cases are failing. Mocha version is 5.2.0

Test cases

enter image description here

How can I make the before block synchronous so that it will move to It block only after it completed the execution?

Upvotes: 0

Views: 927

Answers (1)

Mark
Mark

Reputation: 92461

Mocha understands promises, so you should be able to just return the promise generated by SetA:

before(function() {
  return SetA.setA(); 
});

Also looking at your function SetA -- you are never resolving that promise. You'll need something like:

module.exports = {
    setA: function () {
        return new Promise(function (resolve) { //<< resolve
            setTimeout(function () {
                console.log("aaaa");
                a = 1;
                resolve() //<< call resolve when you're done
            }, 2000)

        })
    }
}

Upvotes: 3

Related Questions