0

Below is the code that I wrote with mocha, chai and supertest. I have a question with regards to the segment of code below that works, with focus on token.

describe('Authenticated userTest', function () {
    var token;

    before(function loginAuth(done) {
        request(app)
            .post("/login/local")
            .send("username=testName")
            .send("password=qwe123QWE")
            .expect(function (res) {
                should.exist(res.body.token);
                token = res.body.token;
            })
            .end(done);
    });

    it('should give me a defined token', function(done) {
        console.log("token is " + token);
        done();
    });
});

Apparently, token is defined all well and good here. However, when I remove the done function as follows:

describe('Authenticated userTest', function () {
    var token;

    before(function loginAuth() { //done is removed here
        request(app)
            .post("/login/local")
            .send("username=testName")
            .send("password=qwe123QWE")
            .expect(function (res) {
                should.exist(res.body.token);
                token = res.body.token;
            })
            .end(); //done is removed here
    });

    it('should give me a defined token', function(done) {
        console.log("token is " + token);
        done();
    });
});

Token becomes undefined. From what I understand, done is a function passed down from the before hook to all the various tests thereafter that starts with it(...) from the inbuilt source code.

Thus, I want to clarify that particular question (if done is passed only across the tests; if done only accepts the err parameter) and why did the token become undefined after removing the done parameter?

Thank you.

Luna
  • 73
  • 1
  • 1
  • 7

1 Answers1

1

Token didn't become undefined... at the point you try to use it, it is still undefined. token has not yet been set because mocha does not know it is working with an async test.

See https://justinbellamy.com/testing-async-code-with-mocha/

Machtyn
  • 2,982
  • 6
  • 38
  • 64