This post is meant to be a quick one for anyone who may face the same challenge. A few days back I began meddling with APIs using Cypress. I could not for the life of me assert against anything inside of the response body.
The Goal
Long story short, using the API at automationexercise.com, my goal was to GET
a list of products and assert that the responseCode
was equal to 200.
The Cypress docs and plenty of online tutorials parse through JSON properties and objects using the below syntax.
In this example, we see that all we need to parse through the JSON is a response, body, the property name, and the value we expect.
Simple right? Not really.
My test was straightforward:
describe ('Products List API', () => {
context("GET /productsList", () => {
it("gets a list of products", () => {
cy.request("GET", "https://automationexercise.com/api/productsList").then((response) => {
expect(response.status).to.eq(200)
expect(response.body.responseCode[0]).to.eq(200) // Troubled assertion
})
})
})
})
For reference, this is a snippet from the Body of the Response:
{
"responseCode": 200,
"products": [
{
"id": 1,
"name": "Blue Top",
"price": "Rs. 500",
"brand": "Polo",
"category": {
"usertype": {
"usertype": "Women"
},
"category": "Tops"
}
}
}
In this example, using the Cypress-provided syntax never worked. Cypress continuously returned errors such as (and similar to):
Investigating
I did some digging and discovered this “bug” from 2020 related to JSON parsing.
While it wasn’t exactly related to what I needed, the comments contained invaluable information.
As you can see, the Cypress-provided syntax is heavily dependent on the content-type
provided in the Request Headers
.
Solution
If the content-type
is not application.json
we need to use JSON.parse
to read the data.
The
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parseJSON.parse()
static method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
The correct syntax should be:
expect(JSON.parse(response.body).responseCode).to.eq(200) //This syntax is required for parsing the JSON because the Response Header include 'content-type text/html; charset=utf-8' and not 'application/json'
This allows us to parse through the JSON and assert that responseCode
is equal to 200. Now the script is happy, Cypress is happy, and we are happy!
Hopefully, this helps those who face the same or a similar challenge.
What challenges have you encountered with API assertions in Cypress? How did you resolve them?