k6chaijs
Note
The source code for this library can be found in the grafana/k6-jslib-k6chaijs GitHub repository.
k6chaijs
is a library to provide BDD assertions in k6 based on ChaiJS. You can use k6chaijs
as an alternative to check and group.
With this library, you get the following:
- BDD style of assertions for more expressive language
- Chainable assertions
- More powerful assertions functions such as:
deep
,nested
,ordered
, etc. - Automatic assertion messages
- Exception handling for better test stability
Installation
This library is hosted on jslib and can be imported in directly in your k6 script.
import { describe, expect } from 'https://jslib.k6.io/k6chaijs/4.3.4.3/index.js';
Alternatively, you can use a copy of this file stored locally. The source code is available on GitHub.
Example
The following example tests a hypothetical HTTP API that returns a JSON array of objects. Copy the following code, and save it as script.js
:
import http from 'k6/http';
import { describe, expect } from 'https://jslib.k6.io/k6chaijs/4.3.4.3/index.js';
export default function testSuite() {
describe('Fetch a list of public crocodiles', () => {
const response = http.get('https://test-api.k6.io/public/crocodiles');
expect(response.status, 'response status').to.equal(200);
expect(response).to.have.validJsonBody();
expect(response.json().length, 'number of crocs').to.be.above(4);
});
}
When you run this test with k6 run script.js
, the output at the end of the test shows:
█ Fetch a list of public crocodiles
✓ expected response status to equal 200
✓ has valid json body
✓ expected number of crocs to be above 4
If you are familiar with k6, the result is the same as using check and group. Note that expect might add or extend the assertion message.
API
API | Description |
---|---|
config | Options to change k6chaijs behaviour. |
describe | A wrapper of group that catches exceptions to allow continuing the test execution. It returns a boolean to indicate the success of all its k6chaijs assertions. |
expect | A wrapper of check that provides BDD style of assertions. |
Plugins
It’s possible to extend the default functionality with Chai plugins. To use a plugin or build a Chai version with plugins, follow the instructions in this example.