Knowledgebase

Setup and Teardown Functions


Background

Being able to execute code pre and post test is common place when running tests. It can be used to prepare the system under test with data, or maybe to trigger the provisioning of an ephemeral environment of the system under test itself, and at the end to reset or take down that what was set up before the test.

In k6 tests there are two life cycle hooks for running code pre and post test, setup() and teardown().

Setup hook

To run code before the test starts, you implement the setup() function:

1
2
3
export function setup() {
    // setup code
}

Teardown hook

To run code after the test has finished, you implement the teardown() function:

1
2
3
export function teardown() {
    // teardown code
}

Passing data from setup() to main and teardown() functions

A convenient thing with how the setup()/teardown() functionality is implemented is that anything returned from the setup() function will be passed as the first argument to both the main function and the teardown() function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
export function setup() {
    let data = { message: "Hello world!" };
    return data;
}

export function teardown(setupData) {
    // this will print "Hello world!" to the terminal
    console.log(setupData.message);
}

export default function(setupData) {
    // this will print "Hello world!" to the terminal
    console.log(setupData.message);
}

Timeout

setup() and teardown() functions have a default timeout of 10 seconds. If you plan to do heavy workload (such as creating multiple accounts or making slow requests) in these functions, you should configure a larger timeout in the options.

1
2
3
4
5
6
7
export function setup() {
  // slow requests... 
}
export let options = {
    setupTimeout: '30s',
    teardownTimeout: '30s',
}

See the k6 docs on the test life cycle for more information.