k6 same environment variables in multiple export functions

1.5k views Asked by At

Can I use same environment variables in multiple export function ?

export function login() {
    group('Login API', function () {
        __ENV.code = 'code getting from api response';
        console.log("code is : " + __ENV.code);             // getting correct value
    });
  group('Login API', function () {
        console.log("code is : " + __ENV.code);             // getting correct value
    });
}

export function api1() {
    group('1. APIs', function () {
        console.log(`code in 1 : ${__ENV.code}`);          // getting undefined value
    });
    group('2. APIs', function () {
        console.log("code in 2 : " + __ENV.code);          // getting undefined value
    })
}

If I'm using same env variable in same export function, then I'm getting correct value. Also I'm able to use same env variable on other pages/screens. But on same page if I'm using that env variable in different export function then I'm getting undefined response. As shown in above code.

What's wrong I'm doing? (I'm new(beginner) in K6)

1

There are 1 answers

0
knittl On

You can only set an environment variable from outside the script, for example by running k6 run -e CODE=abc your_script.js

You have then access to the value "abc" by reading __ENV.CODE in your script. You can not set it to a different value while the script is running (as you have found out).