How to Mock Axios Requests in Cypress
Mocking HTTP requests in Cypress integration tests allows you to
simulate backend responses, test edge cases, and ensure deterministic
test execution without relying on live APIs. Because Axios uses the
standard browser XMLHttpRequest or fetch
adapter under the hood, Cypress can intercept and mock these requests
natively using the cy.intercept() API. This guide explains
how to set up, intercept, and mock Axios requests using static data,
fixtures, and dynamic handlers.
1. Basic Request
Mocking with cy.intercept()
To mock an Axios call, declare cy.intercept() before the
action that triggers the request. Assign an alias using
.as() so your test can explicitly wait for the network call
to finish.
describe('User Dashboard', () => {
it('displays user data from a mocked Axios GET request', () => {
// Intercept the Axios GET request and provide a mock response
cy.intercept('GET', '/api/users', {
statusCode: 200,
body: [
{ id: 1, name: 'Jane Doe' },
{ id: 2, name: 'John Smith' },
],
}).as('getUsers');
// Visit page and trigger the request
cy.visit('/dashboard');
// Wait for the mocked request to resolve
cy.wait('@getUsers');
// Assert UI updates correctly
cy.get('[data-testid="user-list"]').should('contain', 'Jane Doe');
});
});2. Mocking with External Fixtures
For larger payloads, store mock data in the
cypress/fixtures directory and load it directly into your
interceptor.
Assuming cypress/fixtures/users.json contains your mock
data:
it('loads mock data from a fixture file', () => {
cy.intercept('GET', '/api/users', { fixture: 'users.json' }).as('getUsers');
cy.visit('/dashboard');
cy.wait('@getUsers');
cy.get('[data-testid="user-item"]').should('have.length', 2);
});3. Simulating Server and Network Errors
You can test how your application handles Axios error responses by
modifying the statusCode or forcing a network failure.
Simulating a 500 Internal Server Error:
it('displays an error alert on API failure', () => {
cy.intercept('POST', '/api/login', {
statusCode: 500,
body: { message: 'Internal Server Error' },
}).as('loginRequest');
cy.get('button[type="submit"]').click();
cy.wait('@loginRequest');
cy.get('.error-message').should('contain', 'Internal Server Error');
});Simulating a Dropped Connection:
it('handles network-level failures', () => {
cy.intercept('GET', '/api/settings', { forceNetworkError: true }).as('networkFail');
cy.visit('/settings');
cy.wait('@networkFail');
cy.get('.offline-banner').should('be.visible');
});4. Dynamic Request and Response Modification
If you need to inspect outgoing Axios payloads or dynamically alter
the mock response based on request headers or parameters, pass a route
handler function to cy.intercept().
it('dynamically responds based on request body', () => {
cy.intercept('POST', '/api/cart', (req) => {
// Assert Axios sent the correct payload
expect(req.body).to.have.property('itemId', 101);
// Provide custom dynamic response
req.reply({
statusCode: 201,
body: { success: true, cartCount: req.body.quantity },
headers: { 'x-custom-header': 'mocked' },
});
}).as('addToCart');
cy.get('[data-testid="add-btn-101"]').click();
cy.wait('@addToCart');
cy.get('[data-testid="cart-badge"]').should('contain', '1');
});