How to use check function for nested items in http response correctly?

In my test I have the following check conditions:

const success = check(res, {
"status is 200 OK": (res) => res.status === 200,
"content-type is application/json": (res) => res.headers['Content-Type'] === "application/json; charset=utf-8",
"Bets has successfully returned": (res) => JSON.parse(res.body).Result.Bets,
"Bets count > 0": (res) => JSON.parse(res.body).Result.Bets.length > 0,
"BetId has successfully returned": (res) => JSON.parse(res.body).Result.Bets[0].BetId

});

Sometimes “BetId has successfully returned” check doesn’t pass and the following error returns:
time=“2020-07-03T16:53:33+03:00” level=error msg="TypeError: Cannot read property ‘Bets’ of undefined\n\tat BetsHasSuccessfullyReturned.

How to avoid this situation? Is there any way to split the check in the function ?

You can use the Response.json() helper method - it accepts something like a JSONPath as an argument, so you can reference nested values deep into the JSON file without actually raising an exception. Or you can just write a small helper method that always catches the exceptions. Here’s an example of both approaches:

import http from "k6/http";
import { check } from "k6";

function trycatch(f) {
    return function (r) {
        try {
            return f(r);
        } catch (e) {
            console.error(e);
            return false
        }
    }
}

export default function () {
    let response = http.get("https://test-api.k6.io/public/crocodiles/1/");

    check(response, {
        "http2 is used": (r) => r.proto === "HTTP/2.0",
        "status is 200": (r) => r.status === 200,
        "name is bert": (r) => r.json("name") === "Bert",
        "error without exception 1": (r) => r.json("some.invalid.path[1]") === "whatever",
        "error without exception 2": trycatch((r) => r.json().some.invalid.path[1] === "whatever"),
    });

    console.log("finished execution normally")
}
1 Like