0
0
Cypresstesting~15 mins

Asserting response bodies in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify API response body contains expected data
Preconditions (2)
Step 1: Send a GET request to https://api.example.com/users/1
Step 2: Wait for the response
Step 3: Check that the response status code is 200
Step 4: Verify the response body contains the user object with id 1
Step 5: Verify the response body has name field with value 'John Doe'
Step 6: Verify the response body has email field with value 'john.doe@example.com'
✅ Expected Result: The API response status is 200 and the response body contains the correct user data with id 1, name 'John Doe', and email 'john.doe@example.com'
Automation Requirements - Cypress
Assertions Needed:
Response status code is 200
Response body contains user object with id 1
Response body name field equals 'John Doe'
Response body email field equals 'john.doe@example.com'
Best Practices:
Use cy.request() to send API requests
Use .then() to access response and assert
Use should() or expect() for assertions
Avoid hardcoding full response body; assert only needed fields
Use descriptive test names
Automated Solution
Cypress
describe('API Response Body Assertions', () => {
  it('should verify user data in response body', () => {
    cy.request('GET', 'https://api.example.com/users/1')
      .then((response) => {
        expect(response.status).to.equal(200);
        expect(response.body).to.have.property('id', 1);
        expect(response.body).to.have.property('name', 'John Doe');
        expect(response.body).to.have.property('email', 'john.doe@example.com');
      });
  });
});

This test uses cy.request() to send a GET request to the API endpoint.

We use .then() to get the response object and perform assertions.

Assertions check that the status code is 200, meaning success.

We then check the response body has the expected user properties: id, name, and email with correct values.

This approach focuses only on needed fields, making the test clear and maintainable.

Common Mistakes - 3 Pitfalls
Not waiting for the API response before asserting
Asserting the entire response body as a string
{'mistake': 'Using incorrect assertion syntax like expect(response.body.id == 1)', 'why_bad': 'This does not perform an assertion, just a comparison that is ignored.', 'correct_approach': "Use expect(response.body).to.have.property('id', 1) or expect(response.body.id).to.equal(1)."}
Bonus Challenge

Now add data-driven testing to verify user data for user IDs 1, 2, and 3 with their expected names and emails.

Show Hint