Checks are like assertions, but differ in that they don't halt the execution. Instead, they store the result of the check, pass or fail, and let the script execution continue. Take a look at thresholds for a way to halt the execution of a test based on checks.
Checks are great for codifying assertions relating to HTTP requests/responses, such as making sure the response code is an HTTP 2xx:
Sometimes, even an HTTP 200 response can contain an error message. In these situations, consider adding a check to verify the response body, like this:
If you want to verify that the response to a request that k6 sends is of a certain size, you can use a check for that like this:
When you run a script including checks, you can see the outcome of the check calls in the following output:
In the output above you can see that our check "is status 200" was successful 100% of the times it was called.
You may also add multiple checks within a single check() statement, like this:
When this test is executed, the output will look like this:
About Failing Checks
When a check fails, the script will continue executing successfully and will not return a 'failed' exit status. If you need the whole test to fail based on the results of a check, you have to combine checks with thresholds. This is particularly useful in specific contexts, such as integrating k6 into your CI pipelines or receiving alerts when scheduling your performance tests.
Here we can quickly see what checks are failing, and upon clicking on any check, see the count of passes/failures at given points in the test. You can also add the check to the analysis tab, for further comparison with other metrics.