2

I'm currently trying to run Karate tests on a Node project using this library: https://github.com/karatelabs/karate-npm . My script on package json looks like:

{
    "test_karate" : "MY_VARIABLE=STG node karate/test.js karate/tests/WHATEVER_FEATURE.feature"
}

So, based on the value of "MY_VARIABLE" I would like to determine the host for the url on the karate-config.js, but I haven't been able to retrieve the value inside the karate-config.js file.

I have tried: 1.- Create a side script that returns process.env.MY_VARIABLE and trigger it using karate.exec() but it returns undefined. 2.- Passing it as part of the cli "-Dkarate.MY_VARIABLE=STG" or other syntax but it can't be retrieve inside karate-config.js file.

I know Karate it's usually use with maven and Java, but I'm currently using node, I'm expecting to be able to do something like this:

karate-config.js:

let env = process.env.MY_VARIABLE

if(env== "STG"){
 // do something
}else{
// do something
}

1 Answers1

1

Below is the content of karate-config.js and environment information is received by karate.env predefined variable.

function fn() {
  var env = karate.env; // get system property 'karate.env'
  karate.log('karate.env system property was:', env);

  if (!env) {
    env = 'dev';

  }
  var config = {
    env: env,
  }
  if (env == 'dev') {
    config.baseUrl = 'any_url'
  } else if (env == 'e2e') {
    config.baseUrl = 'any_url';
  }
  return config;
}

karate-config.js has karate.env property which can receive the environment using -Dkarate.env=qa

If you need to use your own variable because of some reason then that can be received using karate.properties['MY_VARIABLE'] in config file, you need to pass
-DMY_VARIABLE=STG from CLI.

function fn() {
  var env = karate.env; // get system property 'karate.env'
  karate.log('karate.env system property was:', env);

  if (!env) {
    env = 'dev';
  }
  var config = {
    env: env,
    userDefined: karate.properties['MY_VARIABLE']
  }
  if (env == 'dev') {
    config.baseUrl = 'any_url'
  } else if (env == 'e2e') {
     config.baseUrl = 'any_url'
  }
  return config;
}

karate.properties['MY_VARIABLE'] can be used in feature file as well as below.

  • def myVariable = karate.properties['MY_VARIABLE']
Shreyansh Jain
  • 498
  • 4
  • 7
  • I think OP is referring to environment variables, which needs a slightly different approach, refer: https://stackoverflow.com/a/52821230/143475 – Peter Thomas Jul 09 '23 at 04:53