haders JS file with dependable of the variables

Viewed 37

first Karate is the best tool for API automation. Period. :D

I have setup a file called headers.js. As one of the headers contains the "locale variable" like -> var headers = { 'X-Country-Code': "US" ...} I need that as a global variable to be able to set other variables based on its value, but as it is specifically into the headers function, how I access its value within a karate.feature file?

JS headers.js

function fn() {
  var env = 'us';

  if (!env) {
    env = 'us'; 
    }   
    var headers = { 'X-Country-Code': "us", 'Content-Type': 'application/x-www-form-urlencoded' };
  if (!env) {
    env = 'ca'; 
    }   
    var headers = { 'X-Country-Code': "ca", 'Content-Type': 'application/x-www-form-urlencoded' };
    return headers;

  }
1 Answers

Maybe all you need to do is set a global variable via karate-config.js and then use it everywhere else, including the headers JS function.

Anyway, you can set a variable from JS in extreme cases, this is kind of mentioned in the docs, but easy to miss: https://github.com/intuit/karate#configure-headers

In rare cases you may need to set a variable from this routine, and a good example is to make the generated UUID "visible" to the currently executing script or feature. You can easily do this via karate.set('someVarName', value).

So this should work:

karate.set('currentCountryCode', headers['X-Country-Code']);

But this would be available within a feature file only after an HTTP request was made because the "headers function" is invoked just before the HTTP call. If you need it before, you have to figure out a different approach, and do note that karate.get('someVariableName') can do the reverse of karate.set().

Also remember that if you want to get the headers after an HTTP request was made you can use karate.prevRequest.headers.

Related