Intercept and verify API request using cy.intercept()
Preconditions (3)
✅ Expected Result: The API request to /api/users is intercepted successfully, and assertions on URL, status code, and response body pass.
describe('API request interception with cy.intercept()', () => { it('should intercept GET /api/users and verify response', () => { // Intercept GET requests to /api/users and alias it cy.intercept('GET', '/api/users').as('getUsers') // Visit the page that triggers the API call cy.visit('/users') // Trigger the API call by clicking the Load Users button cy.get('button#load-users').click() // Wait for the intercepted request to complete cy.wait('@getUsers').then(({ request, response }) => { // Assert the request URL path expect(request.url).to.include('/api/users') // Assert the response status code expect(response?.statusCode).to.equal(200) // Assert the response body contains expected user data expect(response?.body).to.have.property('users') expect(response?.body.users).to.be.an('array').and.not.be.empty expect(response?.body.users[0]).to.have.all.keys('id', 'name', 'email') }) }) })
This test uses cy.intercept() to listen for GET requests to the /api/users endpoint and assigns it an alias @getUsers. We visit the page that triggers the API call and click the button that loads users. Then, cy.wait() waits for the intercepted request to complete. Inside the then callback, we assert that the request URL contains the expected path, the response status code is 200, and the response body contains a users array with user objects having id, name, and email keys. This ensures the API call was made correctly and returned expected data.
Now add data-driven testing with 3 different API endpoints to intercept and verify
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