In previous versions of K6 I was able to declare a global variable on the Init and use it anywhere on the code (on the default and also on external methods called from the default). For example:
import { sleep } from 'k6';
import { externalMethod } from '../src/utils.js'
const vars = []
vars["URL"] = "https://test.k6.io";
vars["H1"] = "Hello!!";
export default function ()
{
console.log(vars["H1"]);
externalMethod();
sleep(1);
}
utils.js
import http from 'k6/http';
export function externalMethod()
{
console.log("executing externalMethod..");
http.get(vars["URL"]);
}
Executing k6 run script.js
Ouput with k6:0.41.0
INFO[0000] Hello!! source=console
INFO[0000] executing externalMethod.. source=console
ERRO[0000] ReferenceError: vars is not defined
at externalMethod (file:///scripts/src/utils.js:6:13(9))
at file:///scripts/src/script.js:12:2(10)
at native executor=per-vu-iterations scenario=default source=stacktrace
Ouput with k6:0.36.0
INFO[0000] Hello!! source=console
INFO[0000] executing externalMethod.. source=console
running (00m01.6s), 0/1 VUs, 1 complete and 0 interrupted iterations
default ✓ [======================================] 1 VUs 00m01.6s/10m0s 1/1 iters, 1 per VU
On Test life cycle (k6.io) it mentions that we should declare the gloval vars on the init side, so I assume this is still possible. Am I right?
If not, I would like to confirm. The only way to follow a similar approach would be:
Work with the external input on the init.
Assign all that “data” to a json object on the setup an return it.
Of course I can, but for certain purposes I would like to use Global vars
I know that it is not best practice but as I mentioned it was possible in previous versions and it is metioned on Test life cycle (k6.io) Init test stage “used To”.
You seem to have been using a bug within k6 that was fixed in v0.40. You can found more info in this issue, but this was never suppose to work like it did before and is against what module as suppose to do. If you need to have global variables use the globalThis global object.
I would argue this is not what that part of the “Used to” is supposed to mean, but I definitely can see how it can be confused, so will try to reword it. Thanks for mentioning it
When I wrote, I was thinking of a truncation of sentences like “The function is used to operate the …”. Never thought how this could be interpreted as “Now you’re just somebody that I used to know”. But it definitely could, so we should find a less ambiguous title. There are much less ambiguous ways. I like “Purpose” as pearsone just mentioned.