cypress/ ├── e2e/ # Test specs │ └── api_integration.cy.js ├── fixtures/ # Test data files │ └── user.json ├── support/ # Custom commands and utilities │ ├── commands.js │ └── intercepts.js cypress.config.js # Cypress configuration file
Why intercepting network validates API integration in Cypress - Framework Benefits
- Test Specs (e2e/): Contains test files that define the test scenarios using Cypress commands.
- Support Layer (support/): Holds reusable commands and intercept logic to mock or spy on network requests.
- Fixtures (fixtures/): Stores static test data used to simulate API responses.
- Configuration (cypress.config.js): Manages environment settings like base URLs and timeouts.
Use cypress.config.js to set base URLs for different environments (dev, staging, prod). Use environment variables to switch API endpoints or credentials without changing test code.
import { defineConfig } from 'cypress';
export default defineConfig({
e2e: {
baseUrl: 'https://api.example.com',
env: {
apiKey: 'test-api-key',
environment: 'staging'
},
setupNodeEvents(on, config) {
// setup code
}
}
})Fixtures provide mock data for API responses to test different scenarios reliably.
Use Cypress built-in reporters or plugins like mochawesome to generate readable test reports showing which API calls passed or failed.
Integrate Cypress tests into CI/CD pipelines (GitHub Actions, Jenkins) to run API integration tests automatically on code changes.
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: cypress-io/github-action@v5
with:
start: npm start
wait-on: 'http://localhost:3000'
wait-on-timeout: 60
- Use Network Interception to Spy and Stub: Intercept API calls to verify requests are sent correctly and stub responses to test UI behavior without relying on real backend.
- Keep Tests Independent: Mock API responses so tests do not depend on external services, making them faster and more reliable.
- Use Fixtures for Consistent Data: Store expected API responses in fixtures to reuse and maintain test data easily.
- Validate Both Request and Response: Check that the app sends correct data and handles API responses properly.
- Integrate with CI/CD: Run API integration tests automatically to catch issues early.
Where in this folder structure would you add a new intercept to mock the login API response?
Answer: Add the intercept logic in cypress/support/intercepts.js and call it from your test spec in cypress/e2e/api_integration.cy.js.
Practice
Solution
Step 1: Understand intercept purpose
Intercepting network calls lets tests watch and control API requests and responses.Step 2: Connect intercept to validation
This helps confirm the app sends correct data and reacts properly to API replies.Final Answer:
It allows verifying that the app sends correct requests and handles responses properly. -> Option CQuick Check:
Intercept = Verify API communication [OK]
- Thinking intercept speeds UI rendering
- Believing intercept fixes API errors automatically
- Assuming intercept disables all network calls
Solution
Step 1: Recall Cypress intercept syntax
The correct syntax is cy.intercept(method, url) where method is 'GET' and url is '/api/users'.Step 2: Compare options
cy.interceptGet('/api/users') uses a non-existent command. cy.intercept('/api/users', 'GET') reverses parameters. cy.route('GET', '/api/users') uses deprecated cy.route. cy.intercept('GET', '/api/users') matches the correct syntax.Final Answer:
cy.intercept('GET', '/api/users') -> Option AQuick Check:
cy.intercept(method, url) = correct syntax [OK]
- Swapping method and URL parameters
- Using deprecated cy.route instead of cy.intercept
- Using non-existent commands like cy.interceptGet
cy.intercept('GET', '/api/data', { fixture: 'data.json' }).as('getData');
cy.visit('/dashboard');
cy.wait('@getData').its('response.statusCode').should('eq', 200);Solution
Step 1: Analyze intercept with fixture
Using a fixture returns a mocked response with status code 200 by default.Step 2: Check wait and assertion
cy.wait('@getData') waits for the intercepted call, then asserts response.statusCode equals 200, which is true.Final Answer:
The test will pass because the intercepted response status is 200. -> Option BQuick Check:
Fixture response status = 200 [OK]
- Assuming fixture responses lack status codes
- Forgetting to alias intercept for cy.wait
- Expecting real network calls instead of mocked
cy.intercept('POST', '/api/login', (req) => {
req.reply({ statusCode: 201, body: { success: true } });
}).as('login');
cy.visit('/login');
cy.get('button[type=submit]').click();
cy.wait('@login').its('response.statusCode').should('eq', 201);Solution
Step 1: Check intercept alias usage
The intercept does not have an alias set with .as('login'), so cy.wait('@login') will fail.Step 2: Verify other parts
Status code 201 is valid for POST creation. The selector and req.reply usage are correct.Final Answer:
The intercept is missing an alias '@login' for cy.wait. -> Option AQuick Check:
Missing .as('login') causes cy.wait failure [OK]
- Not adding .as() alias to intercept
- Confusing valid HTTP status codes
- Misunderstanding req.reply usage
Solution
Step 1: Simulate delay correctly in intercept
Using { delay: 2000 } as the static route handler correctly adds a 2-second delay to the response.Step 2: Verify spinner visibility timing
Check the loading spinner is visible before waiting for the delayed response to finish with cy.wait('@getItems').Final Answer:
Use cy.intercept('GET', '/api/items', { delay: 2000 }).as('getItems'); Then check spinner visibility before cy.wait('@getItems'). -> Option DQuick Check:
{ delay: 2000 } simulates slow response [OK]
- Using invalid req.on('response', res => res.setDelay()) syntax
- Calling delay method directly on req
- Checking spinner only after wait instead of before
Ready to prove it?
Pass the test and this pattern moves unknown
