Dynamic response stubbing in Cypress - Build an Automation Script
describe('Dynamic response stubbing test', () => { beforeEach(() => { cy.visit('http://localhost:3000'); }); it('stubs API response dynamically based on userId query parameter', () => { cy.intercept('GET', '/api/user*', (req) => { const userId = req.query.id; if (userId === '1') { req.reply({ statusCode: 200, body: { name: 'Alice' } }); } else if (userId === '2') { req.reply({ statusCode: 200, body: { name: 'Bob' } }); } else { req.reply({ statusCode: 404, body: { error: 'User not found' } }); } }).as('getUser'); // Trigger first request with userId=1 cy.get('#load-user').click(); cy.wait('@getUser'); cy.contains('Alice').should('be.visible'); // Change userId to 2 in the app before clicking again // Assuming there's a way to set userId, e.g., input field with id 'user-id' cy.get('#user-id').clear().type('2'); cy.get('#load-user').click(); cy.wait('@getUser'); cy.contains('Bob').should('be.visible'); }); });
This test visits the page before each test run to start fresh.
We use cy.intercept with a function to check the id query parameter dynamically. Based on the userId, we reply with different stubbed user names.
The alias @getUser helps us wait for the API call to complete before asserting the page content.
We simulate clicking the button to load user data for userId=1 and verify the page shows 'Alice'. Then we change the userId input to '2', click again, and verify the page shows 'Bob'.
This approach ensures dynamic response stubbing based on request parameters, making tests flexible and realistic.
Now add data-driven testing with 3 different userIds (1, 2, 3) and verify the displayed user names or error message accordingly.
Practice
Solution
Step 1: Understand dynamic response stubbing
Dynamic response stubbing allows tests to modify server replies on the fly to simulate various conditions.Step 2: Identify the main goal
This helps test how the app behaves with different data or errors without relying on real server responses.Final Answer:
To change server responses during tests to simulate different scenarios -> Option AQuick Check:
Dynamic stubbing = simulate different server replies [OK]
- Confusing stubbing with speeding up rendering
- Thinking it generates test data automatically
- Mixing it up with recording user actions
cy.intercept in Cypress?Solution
Step 1: Recall cy.intercept syntax for dynamic stubbing
To modify the response dynamically, use a callback with the request object and call req.reply() with the new body.Step 2: Check each option
cy.intercept('GET', '/api/data', (req) => { req.reply({ body: { value: 42 } }) }) correctly uses (req) => { req.reply({ body: ... }) }. cy.intercept('GET', '/api/data', { status: 200, body: { value: 42 } }) is static stubbing, C returns a value incorrectly, D uses res.send which is not Cypress syntax.Final Answer:
cy.intercept('GET', '/api/data', (req) => { req.reply({ body: { value: 42 } }) }) -> Option DQuick Check:
Dynamic stub uses req.reply() callback [OK]
- Using static object instead of callback for dynamic stubbing
- Returning response instead of calling req.reply()
- Using incorrect callback parameter names
cy.intercept('GET', '/api/user', (req) => {
const id = req.query.id
if (id === '1') {
req.reply({ body: { name: 'Alice' } })
} else {
req.reply({ body: { name: 'Guest' } })
}
})The app calls fetch('/api/user?id=1'). What is the response?
Solution
Step 1: Analyze the intercept callback logic
The callback checks req.query.id. If it equals '1', it replies with { name: 'Alice' }, else { name: 'Guest' }.Step 2: Check the request URL query
The app calls '/api/user?id=1', so req.query.id is '1'. Therefore, the response is { name: 'Alice' }.Final Answer:
{ name: 'Alice' } -> Option CQuick Check:
Query id '1' returns Alice [OK]
- Assuming req.query is undefined in Cypress intercept
- Ignoring query parameters in the stub
- Confusing string and number types in comparison
cy.intercept('POST', '/api/login', (req) => {
req.reply({ statusCode: 200, body: { token: 'abc123' } })
})The test fails with an error about req.reply not being a function. What is wrong?
Solution
Step 1: Understand intercept callback parameter
The callback receives an interception object, often namedinterception, which has thereplymethod.Step 2: Identify the naming and usage error
Usingreqas parameter is allowed butreq.replyis not a function because the object is not the request but the interception. The correct approach is to name itinterceptionand callinterception.reply().Final Answer:
The callback parameter should beinterceptionandinterception.replyused -> Option BQuick Check:
Use interception.reply() in intercept callback [OK]
- Confusing request object with interception object
- Using req.reply() which does not exist
- Misnaming callback parameter causing method errors
{ items: ['apple', 'banana'] }. If 'type' is 'vegetable', respond with { items: ['carrot', 'lettuce'] }. Otherwise, respond with { items: [] }. Which code correctly implements this dynamic response stubbing?Solution
Step 1: Identify correct parameter and method usage
The callback parameter should be namedinterception(or similar) and useinterception.reply()to send the response with abodyproperty.Step 2: Check each option for correctness
cy.intercept('GET', '/api/items', (interception) => { const type = interception.query.type if (type === 'fruit') { interception.reply({ body: { items: ['apple', 'banana'] } }) } else if (type === 'vegetable') { interception.reply({ body: { items: ['carrot', 'lettuce'] } }) } else { interception.reply({ body: { items: [] } }) } }) correctly usesinterception.query.typeand callsinterception.reply({ body: ... }). cy.intercept('GET', '/api/items', (req) => { if (req.query.type === 'fruit') { req.reply({ items: ['apple', 'banana'] }) } else if (req.query.type === 'vegetable') { req.reply({ items: ['carrot', 'lettuce'] }) } else { req.reply({ items: [] }) } }) missesbodywrapper. cy.intercept('GET', '/api/items', (req) => { const type = req.query.type if (type === 'fruit') { req.reply({ body: { items: ['apple', 'banana'] } }) } else if (type === 'vegetable') { req.reply({ body: { items: ['carrot', 'lettuce'] } }) } else { req.reply({ body: { items: [] } }) } }) usesreqbutreq.replyis not a function. cy.intercept('GET', '/api/items', (interception) => { const type = interception.query.type if (type === 'fruit') { interception.send({ body: { items: ['apple', 'banana'] } }) } else if (type === 'vegetable') { interception.send({ body: { items: ['carrot', 'lettuce'] } }) } else { interception.send({ body: { items: [] } }) } }) usesinterception.sendwhich is not a Cypress method.Final Answer:
Option A code correctly implements dynamic response stubbing with query check and reply -> Option AQuick Check:
Use interception.reply({ body }) and check interception.query [OK]
- Using req.reply() which is undefined
- Omitting the body wrapper in reply
- Using interception.send() which does not exist
Ready to prove it?
Pass the test and this pattern moves unknown
