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.

To write your first k6 test script, complete the following steps:

  1. Create a new test file in a directory on your machine (for example, a new folder for this journey, or any existing project):

    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 HTTP module:

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

    The http module enables you to make HTTP requests, and the sleep function helps simulate real-world usage by introducing delays between requests.

  3. Define test options to configure the test execution:

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

    This configuration tells k6 to execute the default function 10 times.

  4. Define the default function that contains your test logic:

    JavaScript
    export default function () {
      // Make a GET request to the target URL
     const res = http.get('https://quickpizza.grafana.com');
     check(res, { 'status was 200': (r) => r.status === 200 });
    
      // Sleep for 1 second to simulate real-world usage
      sleep(1);
    }

    The default function is the entry point for your test script. It will be executed repeatedly based on the iterations option you configured.

  5. Save the complete script. Your script.js file should now 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);
    }

    If you encounter syntax errors or 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.


page 4 of 8