Write your first k6 test script
In this milestone, you create your first k6 test script. k6 tests are written using JavaScript or TypeScript, making them accessible to developers and easy to integrate into existing codebases and projects.
Every k6 script follows a common structure with core components: imports for k6 modules, an options block to configure test execution, and a default function that contains the test logic. The default function defines what your test will do and how it will behave during execution.
Generate a test script with k6 new
Rather than writing a test script from scratch, you can use the k6 new command to generate a starter script.
Run the following command in a directory on your machine (for example, a new folder for this journey, or any existing project):
k6 new script.jsThis creates a file called script.js in the current directory with a working k6 test script. You can name the file anything you like, but it should have a .js or .ts extension.
Tip
k6 newsupports different templates for different use cases. The defaultminimaltemplate is a great starting point. To learn more, refer to Create a test script using the CLI.
Customize the script
The generated script already contains the core structure of a k6 test, but you need to customize it for your first test. Open script.js in your code editor and replace the contents with:
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
iterations: 10,
};
export default function () {
const res = http.get('https://quickpizza.grafana.com');
check(res, { 'status was 200': (r) => r.status === 200 });
sleep(1);
}Save the file and take a moment to understand each part of the script:
- Imports: The
httpmodule enables you to make HTTP requests, whilecheckvalidates responses andsleepintroduces delays between iterations to simulate real-world usage. - Options: The
iterations: 10configuration tells k6 to execute the default function 10 times. - Default function: This is the entry point for your test. Each iteration sends a GET request to the QuickPizza demo app, verifies the response status is 200, and then pauses for 1 second.
If you encounter issues with your script, refer to the k6 documentation on writing tests for more examples and guidance.
In the next milestone, you’ll run this test script locally to see k6 in action and view the test results.