Write your first k6 test script
In this milestone, you create your first k6 test script. k6 tests are written in JavaScript, making them accessible and easy to integrate into existing projects.
Optional: In Grafana Cloud, go to Testing & synthetics > Performance, click Create a test, keep Manual selected, and open the Create a script step. Copy the sample script — Grafana already sets your Default project projectID in the sample, which you need when you run with k6 cloud later.
In your terminal, create a new test file:
touch script.jsYou can name the file anything you like, but it should have a
.jsor.tsextension.Open the file in your code editor and import the k6 modules:
import http from 'k6/http'; import { check, sleep } from 'k6';The
httpmodule makes HTTP requests, andsleepsimulates real-world delays between requests.Define the test options to configure execution:
export const options = { iterations: 10, };This tells k6 to execute the default function 10 times.
Define the default function with your test logic:
export default function () { const res = http.get('https://quickpizza.grafana.com'); check(res, { 'status was 200': (r) => r.status === 200 }); sleep(1); }This makes a GET request, verifies a 200 status, and waits 1 second between iterations.
Save the complete script. Your
script.jsfile should contain: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); }
In the next milestone, you run this test locally and review the results in your terminal.