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);
});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); });
Think about what the stub returns when the category query is 'books'.
The stub checks the query parameter 'category'. When it equals 'books', it replies with an array containing one item. So, response.body.length is 1.
You stub a GET request to '/api/users' that returns 2 user objects dynamically. Which assertion correctly checks the response length?
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( /* ??? */ );
Check the correct Cypress syntax for asserting array length.
The have.length(2) assertion checks that the array has exactly 2 items. Other options are invalid syntax or incorrect.
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' } });
}
});cy.intercept('POST', '/api/login', (req) => { if (req.body.username === 'admin') { req.reply({ statusCode: 200, body: { token: 'admin-token' } }); } });
Think about how Cypress parses request bodies in intercept handlers.
In Cypress, req.body is not automatically parsed as JSON in intercept handlers. It is a string unless parsed manually, so req.body.username is undefined.
You want to stub GET requests to '/api/products' and return different products based on the 'type' query parameter. Which code snippet achieves this?
Consider how to match any query parameters and access them dynamically.
Option A uses a wildcard * to match any query parameters and accesses req.query.type to decide the response dynamically. Others either do not match all queries or do not handle dynamic responses.
Choose the best explanation for why dynamic response stubbing is useful in Cypress testing.
Think about how dynamic stubbing helps test different scenarios.
Dynamic response stubbing lets you tailor responses based on request details, so you can test various cases without changing server code or fixtures. This improves test coverage and mimics real-world behavior.