Search code examples
mocha.jssupertest

Unable to pass parameter from the api request to outside


The code below is a simple mocha test where I am trying to pass the value of the variable my_token so that I can use in different tests. Tried all the possibilities but its not working. Not sure what I am doing wrong!

var supertest = require('supertest'),
    api = supertest('www.xyz.com');

    var my_token = 'DID NOT WORK';

    describe('get collars list', function(done) {   

        before(function(done) {
            api.post('/api/v2/auth')
                .send({username:"SP",password:"**"})
                .set('Content-Type', 'application/json')
                .expect(200)
                .end(function (err, res) {                  

                my_token = "worked"

                done();
            });
            console.log ('passing value to the test :  '+ my_token );
        });  

     it('should login', function(done) {     
       console.log (' token passed to test  : ' + my_token);
     });
    });

Solution

  • You do not need done in a test case that doesn't involve asynchronous operation.

    This should work.

    var supertest = require("supertest"),
      api = supertest("www.xyz.com");
    
    var my_token = "DID NOT WORK";
    
    describe("get collars list", function(done) {
      before(function(done) {
        api
          .post("/api/v2/auth")
          .send({ username: "SP", password: "**" })
          .set("Content-Type", "application/json")
          .expect(200)
          .end(function(err, res) {
            my_token = "worked";
    
            done();
          });
        console.log("passing value to the test :  " + my_token);
      });
    
      it("should login", function() {
        console.log(" token passed to test  : " + my_token);
      });
    });