cypressautomation-testing

Selecting API Response JSON Field in Cypress Resulted as Undefined


I have a problem regarding Cypress response evaluation. I'm intercepting a request and trying to get a field which is returned as "Undefined". Here is the structure of the response directly fetched from browser:

[{"hyperparams": {"param1": 50, "param2": 0.1}, "eval_score": 0.41176470588235303}]

The way that I try to get "eval_score" is follows:

cy.wait("@trial").then(({ response }) => {
          expect(response.body[0]["eval_score"]).within(0, 5);
        });

Your help would be appreciated.


Solution

  • The [ you are seeing when logging response.body[0] is indicative you have not deserialised the response. It's a string containing JSON and not the object itself, so 0 is accessing the first character of a string (strings behave like this with array accessors in JS).

    Try

    expect(JSON.parse(response.body)[0]["eval_score"]).within(0, 5);