0
0
Cypresstesting~5 mins

Dynamic response stubbing in Cypress

Choose your learning style9 modes available
Introduction

Dynamic response stubbing lets you change the data a server sends back during tests. This helps you test different situations without changing the real server.

You want to test how your app behaves with different server data without calling the real server.
You need to simulate errors or slow responses from the server to see how your app handles them.
You want to test user flows that depend on changing server responses.
You want to speed up tests by avoiding real network calls.
You want to isolate frontend tests from backend changes.
Syntax
Cypress
cy.intercept(method, url, (req) => {
  req.reply((res) => {
    // modify res.body or res.statusCode dynamically
  })
})

method is the HTTP method like 'GET' or 'POST'.

You can change the response inside req.reply callback before it reaches your app.

Examples
This changes the user list to always return one user named Alice.
Cypress
cy.intercept('GET', '/api/users', (req) => {
  req.reply((res) => {
    res.body = [{ id: 1, name: 'Alice' }]
  })
})
This returns an empty list for page 2 but lets other requests go to the real server.
Cypress
cy.intercept('GET', '/api/items', (req) => {
  if (req.query.page === '2') {
    req.reply({ body: [] })
  } else {
    req.continue()
  }
})
This blocks login for 'admin' user with a 403 error but allows others.
Cypress
cy.intercept('POST', '/api/login', (req) => {
  if (req.body.username === 'admin') {
    req.reply({ statusCode: 403, body: { error: 'Forbidden' } })
  } else {
    req.continue()
  }
})
Sample Program

This test changes the user list response dynamically. If the server returns no users, it adds a default user. Otherwise, it adds an extra user to the list. Then it checks the page shows users including the extra one.

Cypress
describe('Dynamic response stubbing example', () => {
  it('stubs user data dynamically', () => {
    cy.intercept('GET', '/api/users', (req) => {
      req.reply((res) => {
        if (!res.body || res.body.length === 0) {
          res.body = [{ id: 1, name: 'Default User' }]
        } else {
          res.body.push({ id: 2, name: 'Extra User' })
        }
      })
    })

    cy.visit('/users')
    cy.get('.user').should('have.length.greaterThan', 0)
    cy.get('.user').last().should('contain.text', 'Extra User')
  })
})
OutputSuccess
Important Notes

Use req.continue() to let the request go to the real server if you don't want to stub it.

Dynamic stubbing helps test many cases without writing separate static mocks.

Always check your selectors in cy.get() to match your app's HTML structure.

Summary

Dynamic response stubbing changes server replies during tests to simulate different scenarios.

It helps test error handling, different data sets, and speeds up tests by avoiding real network calls.

Use cy.intercept with a callback to modify responses on the fly.