Test Structure
Every k6 test script follows a consistent structure with specific lifecycle functions. Understanding this structure is essential for writing effective load tests.Basic Test Anatomy
A k6 test consists of four main parts:Lifecycle Phases
Init Context
The init context runs once per VU at the beginning of the test. Use it for:- Importing modules
- Loading local files
- Defining test options
- Initializing custom metrics
Setup Function
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
Data returned from setup() is passed to the default function and teardown() function as the first parameter.
Default Function (VU Code)
The default function is the main test logic that each VU executes repeatedly. This is where you:- Make HTTP requests
- Validate responses with checks
- Add think time with sleep
- Record custom metrics
Teardown Function
The teardown function runs once at the end of the test. Use it for:- Cleaning up test data
- Logging final results
- Deleting resources
Execution Order
Here’s how k6 executes your test:If you have 10 VUs, the init code runs 10 times (once per VU), but setup and teardown run only once for the entire test.
Multiple Exported Functions
You can export multiple test functions and use them with scenarios:Best Practices
- Keep init code lightweight - It runs for every VU, so avoid heavy computations
- Use setup for authentication - Get tokens once, not in every iteration
- Add sleep in default function - Simulate realistic user behavior
- Return data from setup - Share authentication tokens and test data
- Clean up in teardown - Remove test data to avoid pollution
Controlling Setup/Teardown
You can skip setup or teardown using options:Next Steps
- Learn about HTTP Requests to make API calls
- Explore Test Options to configure your test
- Understand Scenarios for complex test patterns