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.

  1. In your terminal, create a new test file:

    Bash
    touch script.js

    You can name the file anything you like, but it should have a .js or .ts extension.

  2. Open the file in your code editor and import the k6 modules:

    JavaScript
    import http from 'k6/http';
    import { check, sleep } from 'k6';

    The http module makes HTTP requests, and sleep simulates real-world delays between requests.

  3. Define the test options to configure execution:

    JavaScript
    export const options = {
      iterations: 10,
    };

    This tells k6 to execute the default function 10 times.

  4. Define the default function with your test logic:

    JavaScript
    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.

  5. Save the complete script. Your script.js file should contain:

    JavaScript
    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.


page 4 of 8