0
0
Cypresstesting~5 mins

Asserting response bodies in Cypress

Choose your learning style9 modes available
Introduction

We check response bodies to make sure the server sends the right data. This helps catch mistakes early.

When testing if an API returns the expected user details after login.
When verifying that a product list API returns the correct items.
When checking if a form submission returns a success message in the response.
When confirming that error messages appear correctly in the response body.
When validating that data updates are reflected in the API response.
Syntax
Cypress
cy.request('GET', '/api/data').then((response) => {
  expect(response.body).to.have.property('key', 'value')
})

Use cy.request() to make API calls in Cypress.

Use expect() to check the response body content.

Examples
Checks that the user with ID 1 has the name 'Alice'.
Cypress
cy.request('GET', '/users/1').then((response) => {
  expect(response.body).to.have.property('name', 'Alice')
})
Checks that the login response includes a token property.
Cypress
cy.request('POST', '/login', { username: 'bob', password: '1234' }).then((response) => {
  expect(response.body).to.have.property('token')
})
Checks that the products response is an array and the first item has an id.
Cypress
cy.request('GET', '/products').then((response) => {
  expect(response.body).to.be.an('array')
  expect(response.body[0]).to.have.property('id')
})
Sample Program

This test sends a GET request to '/users/2' and checks the status code is 200. Then it asserts the response body has the correct user id and email.

Cypress
describe('API response body test', () => {
  it('checks user data in response body', () => {
    cy.request('GET', '/users/2').then((response) => {
      expect(response.status).to.eq(200)
      expect(response.body).to.have.property('id', 2)
      expect(response.body).to.have.property('email', 'user2@example.com')
    })
  })
})
OutputSuccess
Important Notes

Always check the response status code before asserting the body.

Use clear property names to avoid confusion in assertions.

Response bodies can be objects or arrays; adjust assertions accordingly.

Summary

Asserting response bodies helps verify the server sends correct data.

Use cy.request() and expect() to check response content.

Check status codes first, then assert body properties carefully.