0
0
Cypresstesting~5 mins

Asserting request properties in Cypress

Choose your learning style9 modes available
Introduction

We check request properties to make sure our app sends the right data to the server. This helps catch mistakes early.

When testing if a form sends the correct data after submission.
When verifying that API calls include the right headers or parameters.
When checking if a button click triggers the expected network request.
When ensuring sensitive data is not sent in requests by mistake.
Syntax
Cypress
cy.intercept('METHOD', 'URL', (req) => {
  expect(req.body.property).to.equal('expectedValue')
})

Use cy.intercept to watch network requests.

Inside the callback, use expect to check request details.

Examples
This checks that the login request sends the username 'user123'.
Cypress
cy.intercept('POST', '/api/login', (req) => {
  expect(req.body.username).to.equal('user123')
})
This verifies the request has an authorization header.
Cypress
cy.intercept('GET', '/api/data', (req) => {
  expect(req.headers).to.have.property('authorization')
})
This confirms the HTTP method is PUT for user update requests.
Cypress
cy.intercept('PUT', '/api/user/*', (req) => {
  expect(req.method).to.equal('PUT')
})
Sample Program

This test watches the POST request to '/api/submit'. It checks that the request body has the name 'Alice' and that age is a number. The test fills a form and submits it to trigger the request.

Cypress
describe('Test request properties', () => {
  it('checks POST request body', () => {
    cy.intercept('POST', '/api/submit', (req) => {
      expect(req.body.name).to.equal('Alice')
      expect(req.body.age).to.be.a('number')
    }).as('submitRequest')

    cy.visit('/form')
    cy.get('input[name="name"]').type('Alice')
    cy.get('input[name="age"]').type('30')
    cy.get('form').submit()

    cy.wait('@submitRequest')
  })
})
OutputSuccess
Important Notes

Always give your intercepts an alias with .as() to wait for them easily.

Assertions inside cy.intercept callbacks run when the request happens.

Use expect from Chai for clear, readable checks.

Summary

Use cy.intercept to watch network requests in Cypress.

Assert request properties inside the intercept callback with expect.

Check body, headers, method, or any request detail to ensure correctness.