Every k6 test script follows a consistent structure with specific lifecycle functions. Understanding this structure is essential for writing effective load tests.
import http from 'k6/http';import { check, sleep } from 'k6';// 1. Init code - runs once per VUexport let options = { vus: 10, duration: '30s',};// 2. Setup code - runs once at test startexport function setup() { // Prepare test data let res = http.get('https://quickpizza.grafana.com/api/auth'); return { token: res.json('token') };}// 3. VU code - runs repeatedly for each VUexport default function (data) { let res = http.get('https://quickpizza.grafana.com', { headers: { 'Authorization': `Bearer ${data.token}` } }); check(res, { 'status is 200': (r) => r.status === 200 }); sleep(1);}// 4. Teardown code - runs once at test endexport function teardown(data) { // Clean up test data console.log('Test completed with token:', data.token);}
The setup function runs once before the test execution begins. It’s ideal for:
Authenticating and retrieving tokens
Creating test data
Preparing the test environment
export function setup() { // Runs once before the test let loginRes = http.post('https://quickpizza.grafana.com/api/login', { username: '[email protected]', password: 'password123' }); return { authToken: loginRes.json('token'), startTime: new Date().toISOString() };}
Data returned from setup() is passed to the default function and teardown() function as the first parameter.