0
0
Cypresstesting~5 mins

Stubbing responses in Cypress

Choose your learning style9 modes available
Introduction

Stubbing responses lets you fake server answers during tests. This helps you test your app without needing a real server.

When the real server is slow or unavailable.
To test how your app handles specific server responses like errors.
To speed up tests by avoiding real network calls.
When you want to test edge cases that are hard to get from the real server.
Syntax
Cypress
cy.intercept(method, url, response).as(alias)

method is the HTTP method like GET or POST.

url is the endpoint you want to stub.

Examples
This stubs a GET request to '/api/users' and returns data from a fixture file named 'users.json'.
Cypress
cy.intercept('GET', '/api/users', { fixture: 'users.json' }).as('getUsers')
This stubs a POST request to '/api/login' and returns a success message with status 200.
Cypress
cy.intercept('POST', '/api/login', { statusCode: 200, body: { success: true } }).as('postLogin')
Sample Program

This test stubs the GET /api/users call to return two users. Then it visits the users page and checks that two user names appear, with the first being 'Alice'.

Cypress
describe('User list test with stub', () => {
  it('shows users from stubbed response', () => {
    cy.intercept('GET', '/api/users', {
      statusCode: 200,
      body: [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]
    }).as('getUsers')

    cy.visit('/users')

    cy.wait('@getUsers')

    cy.get('[data-cy=user-name]').should('have.length', 2)
    cy.get('[data-cy=user-name]').first().should('contain.text', 'Alice')
  })
})
OutputSuccess
Important Notes

Always give your stub an alias with .as() to wait for it easily.

Use fixtures to keep stub data clean and reusable.

Stubbing helps tests run faster and more reliably by avoiding real network calls.

Summary

Stubbing fakes server responses to test your app without a real backend.

Use cy.intercept() with method, url, and response to stub.

Alias stubs to wait for them and check app behavior.