Test Overview
This test uses cy.intercept() to intercept a network request and verify that the intercepted response contains the expected data.
This test uses cy.intercept() to intercept a network request and verify that the intercepted response contains the expected data.
describe('API request interception test', () => { it('intercepts GET /api/users and checks response', () => { cy.intercept('GET', '/api/users', { statusCode: 200, body: { users: [{ id: 1, name: 'Alice' }] } }).as('getUsers'); cy.visit('/users'); cy.wait('@getUsers').its('response.statusCode').should('eq', 200); cy.get('#user-list').should('contain.text', 'Alice'); }); });
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | cy.intercept() is set up to intercept GET requests to /api/users and respond with a mocked user list | Test runner is ready, intercept is active | — | PASS |
| 2 | cy.visit('/users') navigates the browser to the users page | Browser loads the /users page, triggering the GET /api/users request | — | PASS |
| 3 | cy.wait('@getUsers') waits for the intercepted GET /api/users request to complete | Intercepted request completes with mocked response | Check that response status code equals 200 | PASS |
| 4 | cy.get('#user-list') finds the user list element and checks it contains text 'Alice' | User list element is visible on the page with mocked user data | Verify that user list contains 'Alice' | PASS |
cy.intercept() in Cypress testing?cy.intercept()cy.intercept('GET', '/api/data', { statusCode: 404, body: { error: 'Not found' } }).as('getData')
cy.visit('/data-page')
cy.wait('@getData').then(({ response }) => {
console.log(response.statusCode)
})cy.wait waits for the intercepted request. The response object uses response.status (which is 404), but the code logs response.statusCode, which is undefined.cy.intercept('GET', '/api/items', (req) => {
req.reply({ status: 201, body: { id: 1 } })
})cy.intercept() usage correctly simulates a 2-second delay with a 200 status and a JSON body { success: true }?Pass the test and this pattern moves unknown