Knowledgebase

Structure of a Test Script


Background

Explanation of the breakdown of the different parts of a test script, and what they are used for.


A k6 test script can be broken down into four distinct life-cycle stages.

This can be illustrated by looking at a skeleton of k6 test:

1
2
3
4
5
6
7
8
9
10
11
12
13
// 1. init code

export function setup() {
    // 2. setup code
}

export default function(data) {
    // 3. vu code
}

export function teardown(data) {
    // 4. teardown code
}

It can also be visualized like this:

k6 execution breakdown

Init code

Init code is run once per VU, when the VU is initialized. This is the only place where interacting with files is allowed, via the open() API.

See the k6 docs on init code for more information.

VU code

The VU code is the code that contains the actual testing logic. This code is executed from top to bottom. If you have test duration that is longer than the time it takes to run through one iteration of the VU code it will loop, and start executing again from the top of this default function over and over until the test duration finalizes.

1
2
3
export default function(data) {

}

Setup/teardown life-cycle hooks

The setup() and teardown() functions are life-cycle hooks that are run once pre and post test respectively. See article on setup/teardown life-cycle hooks for more details.

1
2
3
4
5
6
7
export function setup() {

}

export function teardown(data) {

}