Bird
Raised Fist0
Cypresstesting~20 mins

Dynamic response stubbing in Cypress - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Dynamic Stubbing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Cypress test with dynamic response stubbing?

Consider this Cypress test that stubs a GET request dynamically based on the query parameter.

cy.intercept('GET', '/api/items*', (req) => {
  const category = req.query.category;
  if (category === 'books') {
    req.reply({ body: [{ id: 1, name: 'Book A' }] });
  } else {
    req.reply({ body: [] });
  }
}).as('getItems');

cy.visit('/items?category=books');
cy.wait('@getItems').then(({ response }) => {
  console.log(response.body.length);
});
Cypress
cy.intercept('GET', '/api/items*', (req) => {
  const category = req.query.category;
  if (category === 'books') {
    req.reply({ body: [{ id: 1, name: 'Book A' }] });
  } else {
    req.reply({ body: [] });
  }
}).as('getItems');

cy.visit('/items?category=books');
cy.wait('@getItems').then(({ response }) => {
  console.log(response.body.length);
});
A0
B1
Cundefined
DTypeError
Attempts:
2 left
💡 Hint

Think about what the stub returns when the category query is 'books'.

❓ assertion
intermediate
2:00remaining
Which assertion correctly verifies the dynamic stubbed response contains 2 users?

You stub a GET request to '/api/users' that returns 2 user objects dynamically. Which assertion correctly checks the response length?

Cypress
cy.intercept('GET', '/api/users', (req) => {
  req.reply({ body: [{ id: 1 }, { id: 2 }] });
}).as('getUsers');

cy.visit('/users');
cy.wait('@getUsers').its('response.body').should( /* ??? */ );
Ahave.length(2)
Bequal(2)
Ccontain.length(2)
Dlength.equal(2)
Attempts:
2 left
💡 Hint

Check the correct Cypress syntax for asserting array length.

🔧 Debug
advanced
2:00remaining
Why does this dynamic stub not work as expected?

Examine this Cypress intercept code. It should stub different responses based on the request body, but always returns the same response.

cy.intercept('POST', '/api/login', (req) => {
  if (req.body.username === 'admin') {
    req.reply({ statusCode: 200, body: { token: 'admin-token' } });
  }
});
Cypress
cy.intercept('POST', '/api/login', (req) => {
  if (req.body.username === 'admin') {
    req.reply({ statusCode: 200, body: { token: 'admin-token' } });
  }
});
AThe req.reply is called twice causing a conflict.
BThe stub does not handle non-admin usernames, so requests without 'admin' hang.
CThe intercept URL pattern is incorrect and does not match the request.
DThe req.body is undefined because the request is not parsed automatically.
Attempts:
2 left
💡 Hint

Think about how Cypress parses request bodies in intercept handlers.

❓ framework
advanced
2:00remaining
Which Cypress command correctly stubs a dynamic GET response based on URL parameters?

You want to stub GET requests to '/api/products' and return different products based on the 'type' query parameter. Which code snippet achieves this?

A
cy.intercept('GET', '/api/products*', (req) => {
  const type = req.query.type;
  if (type === 'electronics') {
    req.reply({ body: [{ id: 1, name: 'Phone' }] });
  } else {
    req.reply({ body: [] });
  }
});
B
cy.intercept('GET', '/api/products', (req) => {
  if (req.url.includes('type=electronics')) {
    req.reply({ body: [{ id: 1, name: 'Phone' }] });
  } else {
    req.reply({ body: [] });
  }
});
C
cy.intercept('GET', '/api/products?type=electronics', (req) => {
  req.reply({ body: [{ id: 1, name: 'Phone' }] });
});
Dcy.intercept('GET', '/api/products', { body: [{ id: 1, name: 'Phone' }] });
Attempts:
2 left
💡 Hint

Consider how to match any query parameters and access them dynamically.

🧠 Conceptual
expert
2:00remaining
What is the main advantage of dynamic response stubbing in Cypress tests?

Choose the best explanation for why dynamic response stubbing is useful in Cypress testing.

AIt speeds up tests by caching all responses and never making network calls.
BIt automatically generates test data without needing manual input or fixtures.
CIt allows tests to simulate different server responses based on request data, improving test coverage and realism.
DIt replaces the need for writing assertions by validating responses automatically.
Attempts:
2 left
💡 Hint

Think about how dynamic stubbing helps test different scenarios.

Practice

(1/5)
1. What is the main purpose of dynamic response stubbing in Cypress tests?
easy
A. To change server responses during tests to simulate different scenarios
B. To speed up the browser rendering process
C. To automatically generate test data from the server
D. To record user interactions for playback

Solution

  1. Step 1: Understand dynamic response stubbing

    Dynamic response stubbing allows tests to modify server replies on the fly to simulate various conditions.
  2. Step 2: Identify the main goal

    This helps test how the app behaves with different data or errors without relying on real server responses.
  3. Final Answer:

    To change server responses during tests to simulate different scenarios -> Option A
  4. Quick Check:

    Dynamic stubbing = simulate different server replies [OK]
Hint: Dynamic stubbing means changing server replies during tests [OK]
Common Mistakes:
  • Confusing stubbing with speeding up rendering
  • Thinking it generates test data automatically
  • Mixing it up with recording user actions
2. Which of the following is the correct way to stub a dynamic response using cy.intercept in Cypress?
easy
A. cy.intercept('GET', '/api/data', { status: 200, body: { value: 42 } })
B. cy.intercept('GET', '/api/data', (res) => { res.send({ value: 42 }) })
C. cy.intercept('GET', '/api/data', () => { return { value: 42 } })
D. cy.intercept('GET', '/api/data', (req) => { req.reply({ body: { value: 42 } }) })

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    cy.intercept('GET', '/api/data', (req) => { req.reply({ body: { value: 42 } }) }) -> Option D
  4. Quick Check:

    Dynamic stub uses req.reply() callback [OK]
Hint: Use req.reply() inside intercept callback for dynamic response [OK]
Common Mistakes:
  • Using static object instead of callback for dynamic stubbing
  • Returning response instead of calling req.reply()
  • Using incorrect callback parameter names
3. Given the following Cypress code, what will be the response body when the app requests '/api/user'?
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?

medium
A. Empty response body
B. { name: 'Guest' }
C. { name: 'Alice' }
D. An error occurs because req.query is undefined

Solution

  1. 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' }.
  2. 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' }.
  3. Final Answer:

    { name: 'Alice' } -> Option C
  4. Quick Check:

    Query id '1' returns Alice [OK]
Hint: Match query params in req.query to decide response [OK]
Common Mistakes:
  • Assuming req.query is undefined in Cypress intercept
  • Ignoring query parameters in the stub
  • Confusing string and number types in comparison
4. Identify the error in this Cypress dynamic stub code:
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?

medium
A. The callback receives req but req.reply is not a function; should use req.continue
B. The callback parameter should be interception and interception.reply used
C. The callback parameter is correct, but req.reply is only available on res
D. The callback parameter should be named res instead of req

Solution

  1. Step 1: Understand intercept callback parameter

    The callback receives an interception object, often named interception, which has the reply method.
  2. Step 2: Identify the naming and usage error

    Using req as parameter is allowed but req.reply is not a function because the object is not the request but the interception. The correct approach is to name it interception and call interception.reply().
  3. Final Answer:

    The callback parameter should be interception and interception.reply used -> Option B
  4. Quick Check:

    Use interception.reply() in intercept callback [OK]
Hint: Use interception.reply(), not req.reply(), in intercept callback [OK]
Common Mistakes:
  • Confusing request object with interception object
  • Using req.reply() which does not exist
  • Misnaming callback parameter causing method errors
5. You want to stub a GET request to '/api/items' so that the response body depends on a query parameter 'type'. If 'type' is 'fruit', respond with { items: ['apple', 'banana'] }. If 'type' is 'vegetable', respond with { items: ['carrot', 'lettuce'] }. Otherwise, respond with { items: [] }. Which code correctly implements this dynamic response stubbing?
hard
A. 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: [] } }) } })
B. 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: [] }) } })
C. 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: [] } }) } })
D. 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: [] } }) } })

Solution

  1. Step 1: Identify correct parameter and method usage

    The callback parameter should be named interception (or similar) and use interception.reply() to send the response with a body property.
  2. 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 uses interception.query.type and calls interception.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: [] }) } }) misses body wrapper. 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: [] } }) } }) uses req but req.reply is 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: [] } }) } }) uses interception.send which is not a Cypress method.
  3. Final Answer:

    Option A code correctly implements dynamic response stubbing with query check and reply -> Option A
  4. Quick Check:

    Use interception.reply({ body }) and check interception.query [OK]
Hint: Use interception.reply({ body }) and check interception.query.type [OK]
Common Mistakes:
  • Using req.reply() which is undefined
  • Omitting the body wrapper in reply
  • Using interception.send() which does not exist
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard