0

I am currently using Chakram API Testing framework to test some REST API endpoints.

The first API gets a CSRF token which is used in the rest of the endpoints in the headers.

The CSRF API returns a JSON object - something like this

{
csrf_token : Aajkndaknsda99/adjaj29adja
}

This is how I'm doing it right now

    describe('Hits the CSRF API to get the token',()=>{

        let csrf_tok;
                before(()=>{
                 return chakram.wait(response = chakram.get(API_ENDPOINT,headers));
    });

       it('gets the csrf token from the response',()=>{
        return response.then(function(resp){

             csrf_tok = response.body.csrf_token;
             console.log(csrf_tok) //works fine and I can see the value correctly
             exports.csrf = csrf_tok;

       });
     });
    });

In my other file, where I need to use the CSRF token, I'm doing something like this

var token = require('../test/csrf_token');
   var options ={
       headers :{
        //other headers
        CSRF-TOKEN : token.csrf;
}
}

However, this is not working and the rest of the API endpoint tests are failing due to the token being passed as undefined. I hard coded the value of token and then the tests starts working. However, I do not want to do this every time (I plan on deploying this as a part of pipelines).

This issue seems to be that the variable cannot be accessed outside of Mocha's describe context. Is that right? If so, how can I overcome it?

demouser123
  • 4,108
  • 9
  • 50
  • 82

2 Answers2

0

You can declare the variable outside describe and then export it from outside 'describe'.

Other thing I have noticed regarding line:

csrf_tok = response.body.csrf_token;

It should be :

csrf_tok = resp.response.body.csrf_token;
demouser123
  • 4,108
  • 9
  • 50
  • 82
Dinesh Kumar
  • 1,694
  • 15
  • 22
0

This doesnt answer your specific question, but I needed something similar - where I needed to get an auth token that could then be passed to other tests. I did this with a before hook in a shared.js file

before ( function getToken (done) {
  chai.request(host)
  .post(tokenURL)
  .send({my params})
  .end(function(err, response){
     ... getToken expectations
     this.myToken = response.token;
     done();
  });
});

Then in test.js file you can just use 'myToken', as long as your shared.js file is in the root test dir See https://gist.github.com/icirellik/b9968abcecbb9e88dfb2

Marla
  • 61
  • 5