Verify API response body contains expected data
Preconditions (2)
✅ 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'
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.
Now add data-driven testing to verify user data for user IDs 1, 2, and 3 with their expected names and emails.
name equal to "John" in Cypress?cy.request() returns a response object. To assert a property in the body, use its('body') to access it.should('have.property', key, value) for assertionshould('have.property', 'name', 'John').cy.request('/api/data').then((response) => {
expect(response.status).to.eq(200)
expect(response.body.items).to.have.length(3)
})response.status to equal 200, so the server must respond with HTTP 200.response.body.items to have exactly 3 elements. If it has more or less, the test fails.success is true:
cy.request('/api/submit').then((response) => {
expect(response.body.success).to.be.true()
})to.be.true is a property, not a function, so it should not have parentheses.response.body.success is valid if the property exists.id equal to 5 and a roles array containing "admin". Which Cypress assertion correctly checks both conditions?should with a callback allows multiple assertions on the body object.expect(body.id).to.eq(5) checks the id correctly. expect(body.roles).to.include('admin') checks the roles array contains 'admin'.Pass the test and this pattern moves unknown