Nathan Martins Nathan Martins - 1 month ago 8
Node.js Question

Storing a MongoDb result in a variable to run a Mocha test, getting undefined

So, I'm trying to run a Mocha test, more precisely a Chakram test.
The problem is, I'm getting data from a collection in MongoDB and I want to store that data in a global variable to run some tests.
The problem is that inside the call back I get the data, but it doesn't set the global variables to run the tests.

Here is the code

var chakram = require('chakram'),
expect = chakram.expect;

describe("Test", function() {
var gl_email;
var gl_token;

before("Getting user data", function() {

var setAccessData = function() {
var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost/virtusapp', function(err, db) {
if (err) throw err;
console.log("Connected to Database");
var user = db.collection('users').findOne({
name: "virtus-app"
});
user.then(function(result) {
email = result.email;
token = result.token1 + result.token2;
db.close(test(email, token))
});
});
}

var test = function(email, token) {
gl_email = email;
gl_token = token;

//Here the email and token are set, but it doesnt set the global variables

}

setAccessData();
});

it("should have set global email variable", function() {

//here gl_email should be set, but I get UNDEFINED.

expect(gl_email).to.eql("virtus-app@virtus.ufcg.edu.br");
})
});


I believe that the problem is not with Chakram, because I haven't used in this code yet.

Answer

Your before function is asynchronous. You should use a different signature to tell mocha that it has to wait until it's finished before running the tests.

before("Getting user data", function(done) {
...

    var test = function(email, token) {
        gl_email = email;
        gl_token = token;

        done();

    }
...
});

Only after done() is called the rest of the code is going to be executed by mocha.

Mocha docs has a very comprehensive guide on how to test asynchronous code https://mochajs.org/#asynchronous-code