Chai Assertion Library is an assertion library that is paired with k6 to provide a more developer-friendly BDD and TDD assertion style. It's a more powerful alternative to the k6-native check() and group().
This library is recommended for any type of testing, but especially for:
- Functional testing, where many asserts are needed.
- Stress testing, where the System Under Test is failing and the test code needs to stay robust.
- Load testing, when the test should abort as soon as the first failure occurs.
There's nothing to install. This library is hosted on jslib and can be imported in the k6 script directly.
Alternatively, you can use a copy of this file stored locally.
Let's get started by writing a test for a hypothetical HTTP API that should return a JSON array of objects.
First, create a mytest.js k6 script file.
If you are familiar with k6, this is similar to using the built-in group and check functionalities but with different names.
When you run this test with k6 run mytest.js the result should look similar to this:
This basic example is not very exciting because you can get the same result with group and check. So let's move on to more interesting examples.
When writing integration tests and performance test, it's often necessary to execute conditional checks. For example, you may want to inspect the JSON body only when the http response is 200, ignoring the bodies of all other status codes.
Unlike check(), when expect() fails, it stops the execution of the following assertions in the entire describe()group.
After executing, this script should print the following:
When the status code isn't 200, the remaining two calls to expect() are omitted and the result looks like this.
Because of the threshold, k6 will exit with non-zero exit code.
All examples documented in Chai's official API documentation are runnable in k6. For specific APIs, please refer to the official documentation.
For more advanced examples, see the examples section
Chai exposes a number of configuration options that can change how the library behaves. See configuration.
It's possible to extend the Chaijs default functionality with additional plugins. See plugins.