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.
Dynamic response stubbing in 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.
cy.intercept('GET', '/api/users', (req) => { req.reply((res) => { res.body = [{ id: 1, name: 'Alice' }] }) })
cy.intercept('GET', '/api/items', (req) => { if (req.query.page === '2') { req.reply({ body: [] }) } else { req.continue() } })
cy.intercept('POST', '/api/login', (req) => { if (req.body.username === 'admin') { req.reply({ statusCode: 403, body: { error: 'Forbidden' } }) } else { req.continue() } })
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.
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') }) })
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.
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.