warningexpect.js library is no longer maintained
expect.js library has been deprecated in favor of Chaijs.
Please migrate to the k6Chaijs library. The documentation below is retained for historical reasons.
When executing a performance or integration test, you should expect that your system under test may crash. If this happens, your test should print useful information rather than stack traces caused by unexpected HTTP responses.
expect library is designed to make it easy to write test scripts that are resilient to failing SUT (System Under Test).
It's not uncommon for performance testers to write fragile code that assumes the http response will contain expected data.
Fragile code is most clearly demonstrated with an example.
This code will work fine as long as SUT (System Under Test) returns correct responses. When the SUT starts to fail, there's a good chance the r.json().length will throw an exception similar to
In this example, the system was overloaded, and the load balancer returned a 503 response that did not have a valid JSON body. k6 has thrown a JavaScript exception and restarted execution from the beginning. This test code is fragile to failing SUT because the first check does not prevent the second check from executing. It's possible to rewrite this code to be less fragile, but that will make it longer and less readable.
Error handling of this type happens automatically when using the expect.js library. When the first expect fails, the remaining checks in the chain are not executed, and the test is marked as failed — the execution proceeds to the next describe() instead of restarting from the top.
Handling exceptions
Sometimes it's hard to predict the way SUT can fail. For those cases, the expect library caught any exceptions thrown inside of describe() body, and records it as a failed condition.
Execution of this script should print the following output.