Skip to content

Add example for using global variables #1920

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions docs/sources/k6/next/examples/use-global-variables.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
---
title: 'Use global variables in k6'
description: 'Learn how and when to use global variables in k6.'
weight: 13
---

# Use global variables in k6

A global variable is a variable that can be accessed from any scope. In the context of k6, global variables can be used to persist and pass information across iterations of a test run, and must be declared in the [`init` stage](https://grafana.com/docs/k6/<K6_VERSION>/using-k6/test-lifecycle/#the-init-stage).

A common use case is when you need to extract a value from a page, such as a CSRF or an API token, and reuse that across iterations of your test.

There are multiple ways to use global variables in JavaScript, each with benefits and drawbacks.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is an important caveat we should mention somehow here, which is that modification of variables defined in the init context will be local to the VUs they're made in.

An expectation I often see arise from users is to treat global objects defined in the init context, as if they were just that: a standard JS object that you can modify during your test. However, because k6 is essentially a worker pool, and our workers (VUs) work in isolation from each other, that assumption does not convert to reality for most uses.

So in practice, if the example was setting options to define say 8 VUs, and a multiple of 8 iterations, then each execution of the default function would see a prop value that's local to the VU executing the iterations.

In practice, my observation is that most users will expect that with 2 VUs and 4 iterations, incrementing the var prop would lead to its value being 8 at the end of the test, whereas in reality it will be 4 for the first VU, and 4 for the second VU.

I would keep the example as-is, but somehow remind the VU model, and insist that for read-only use-cases, where users either use a static value in their global object, or set it only once at the begining of the test (in setup for instance); no problem. But as soon as they write to it, they need to be aware that the code is gonna be executed concurrently, and that each VU will have its own VARS instance.

I realize this might be a somewhat hairy explanation, but happy to pair on this 🙇🏻


## Option 1: use `import` and `export`

The first option is to declare a global variables object in your main script and export it.

```js
import { doSomething, doSomethingElse } from './imported-script.js';

export const VARS = {};

export default function () {
VARS.prop = 'prop1';

doSomething();

doSomethingElse();
console.log(JSON.stringify(VARS));
}
```

You can then import the variable in your script, and use it across functions or alter the values:

```js
import { VARS } from './main.js';

export function doSomething() {
console.log(JSON.stringify(VARS));
}

export function doSomethingElse() {
VARS.prop2 = 'prop2';
}
```

The advantage of using this method is the fact that you need to explicitly use the `import` and `export` statements. That can make it easier when working in a team, so other developers can understand your script logic and see where the variables and values came from.

## Option 2: use `globalThis`

The second option is to use the `globalThis` JavaScript object, which is available in any JavaScript environment, not just k6.

For example, in your main script you can add a property to `globalThis`:

```js
import { doSomething, doSomethingElse } from './imported-script.js';

globalThis.VARS = {};

export default function () {
globalThis.VARS.prop = 'prop1';

doSomething();

doSomethingElse();
console.log(JSON.stringify(globalThis.VARS));
}
```

And, similarly to the previous option, you can use access it from anywhere in that script or in imported scripts as well:

```js
export function doSomething() {
console.log(JSON.stringify(globalThis.VARS));
}

export function doSomethingElse() {
globalThis.VARS.prop2 = 'prop2';
}
```

The advantage to using the `globalThis` object is that you don't need to `import` or `export` a global variable. The downside is that, depending on how complex or extensive your test scripts are, using the `globalThis` variable can make your script more verbose, and cause unintended behavior if you're not careful about how you're using and setting global variables.