Rayn D Rayn D - 4 months ago 10
Node.js Question

Unit test with promise not working

Im using mocha to test my api, the problem is that this function is async and
the test suite called before I getting the resutls from the function, how can I overcome this?

I try to chain the test like following which raise an error Empty test suite.

describe("Validations", function () {

var validator = require('../utils/validator');
var isValid = null;

validator.validateJS()
.then(function (args) {
isValid = args;
}).then(function(){
it("init validations ", function () {
expect(isValid).to.equal('valid1');
});
});

})


My initial usage is like following which if is call to the it and expect inside before the
answer(isValid) is coming from the promise,any idea?

describe("Validations", function () {

var validator = require('../utils/validator');
var isValid = null;



validator.validateJS()
.then(function (args) {
isValid = args;

}).done();

it("init validations ", function () {
expect(isValid).to.equal('valid1');
});

})

Answer

Use mocha's before().

describe("Validations", function () {

    var validator = require('../utils/validator');
    var isValid = null;

    before(function(done) {
        validator.validateJS()
        .then(function (args) {
            isValid = args;
            done();
        })
    })

    it("init validations ", function () {
        expect(isValid).to.equal('valid1');
    });
})