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.