Knowledgebase

Checks


Background

Checks are like asserts but differ in that they don’t halt the execution of the test if a false result is encountered, instead the pass/fail result of the check is stored and the test continues executing.


Example

Use checks to evaluate if functional pass/fail conditions are met during test execution. In our below example, we evaluate if a status code of 200 is returned:

1
2
3
4
5
6
7
8
9
import { check } from "k6";
import http from "k6/http";

export default function() {
  let res = http.get("http://test.loadimpact.com/");
  check(res, {
    "is status 200": (r) => r.status === 200
  });
}

Note: In order to utilize custom metrics, you MUST import { check } from "k6"; within the init context of your script.


Best Practice Example: Failing a test using thresholds

Checks on their own can’ t fail a test, you need to combine them with custom metrics and thresholds to specify failure criteria.

In the below example we set a threshold that specifies we accept a maximum 10% check failure rate before considering the test a failure:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import http from "k6/http";
import { check } from "k6";
import { Rate } from "k6/metrics";

export let errorRate = new Rate("errors");

export let options = {
    thresholds: {
        "errors": ["rate<0.1"],
   }
};

export default function() {
    let success = check(http.get("http://test.loadimpact.com"), {
        "status is 200": (r) => r.status == 200
    });
    if (!success) {
        errorRate.add(1);
    }
};

See also: