expect.js library has been deprecated in favor of Chaijs.
Please migrate to k6Chaijs library. The documentation below is retained for historical reasons.
This library is especially useful 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, where the failures of the System Under Test need to be robustly collected for analysis
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 functionality 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 the same result can be achieved 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. If it's 500, the body is not relevant and should not be inspected.
It's possible to chain checks using the .and() function, as shown below.
When you run this test with k6 run mytest.js, the result should look similar to this:
The above script should result in the following being printed after execution:
More advanced examples can be found in the examples section
|describe(name, function)||Entry point for creating tests.|
|expect(value)||expect(value) sets the value to be used in comparison by the next function in the chain|
|and(value)||and(value) is similar to expect(value), but can be used in a chain.|
|as(alias)||as(alias) sets a textual representation of the value passed to expect or and.|
|toEqual(value)||The .toEqual(expectedValue) is similar to ===|
|toBeGreaterThan(expectedValue)||Use to verify that received > expected|
|toBeGreaterThanOrEqual(expectedValue)||Use to verify that received >= expected|
|toBeLessThan(expectedValue)||Use to verify that received < expected|
|toBeLessThanOrEqual(expectedValue)||Use to verify that received <= expected|
|toBeBetween(from, to)||Use to verify that expected value is within range.|
|toBeTruthy()||Use .toBeTruthy when you don't care what a value is and you want to ensure a value is true in a boolean context.|
|toHaveValidJson()||Use to verify that the http response has a valid JSON body.|