Search code examples
javascriptcypress

Unable to verify value from response in Cypress


I am trying to verify value of key in my endpoint response using Cypress, I want to verify that responseCode should be equal to 400, but it is returning me undefined value.

I am using the following logic:

describe("Veriy Login", () => {
  context("Verify Login", () => {
    it("Verify User Login", () => {
      cy.request({
        method: "POST",
        url: "https://automationexercise.com/api/verifyLogin?email=login_user_123@test.com&password=Test@12345",
      }).should((response) => {
        expect(response.status).to.eq(200);
        expect(response
            .body.responseCode)
        .to.eq(400);
      });
    });
  });
});

and when I ran this on Cypress runner, I am getting response which can be viewed on screenshot:

enter image description here

Following is the response:

{
    "responseCode": 400,
    "message": "Bad request, email or password parameter is missing in POST request."
}

What am I missing?


Solution

  • Logic is

    • response.status is 200
    • so response.body part is correct (status & body are common properties, if one is present the other is present
    • response.body.responseCode is undefined
    • => therefore response.body is string type

    So convert to JSON

    expect(JSON.parse(response.body).responseCode).to.eq(400)