When using Cypress to test a web app, why is intercepting network requests important for validating API integration?
Think about how you can confirm the app talks correctly to the backend.
Intercepting network requests lets you see the real data sent and received. This confirms the app and API work together as expected.
Consider this Cypress test snippet that intercepts a GET request and checks the response status:
cy.intercept('GET', '/api/items', { statusCode: 200, body: [{ id: 1, name: 'Item1' }] }).as('getItems')
cy.visit('/items')
cy.wait('@getItems').its('response.statusCode').should('eq', 200)What will be the test result?
Check the status code in the intercept and assertion.
The intercept mocks the GET /api/items call with a 200 status and a body. The test waits for this call and asserts the status code is 200, so it passes.
Given this intercepted API call in Cypress:
cy.intercept('POST', '/api/login', { statusCode: 200, body: { token: 'abc123' } }).as('login')Which assertion correctly checks that the response body contains the token 'abc123'?
Remember to check the response body, not the request body.
Option A correctly waits for the alias, accesses the response body token, and asserts its value. Others either check wrong properties or use invalid commands.
Look at this Cypress test code:
cy.intercept('GET', '/api/data').as('getData')
cy.visit('/dashboard')
cy.wait('@getData').its('response.statusCode').should('eq', 200)The test fails with a timeout waiting for '@getData'. What is the most likely reason?
Think about whether the app triggers the expected API call.
If the app never calls the GET /api/data endpoint during the visit, the alias '@getData' is never triggered, causing cy.wait to timeout.
In what way does using Cypress's network intercept feature improve the reliability of API integration tests compared to relying on live API calls?
Consider how controlling API responses affects test stability.
Intercepting network calls lets tests use fixed responses, so tests don't fail due to slow or changing backend behavior, making them more reliable.