Mock Network Timeouts and Dropped Connections in Axios
Testing how your application handles unstable network conditions is
essential for building resilient frontend and backend services. This
article demonstrates how to mock network timeouts, dropped connections,
and aborted requests when using the Axios HTTP client. You will learn
how to implement these tests primarily using the popular
axios-mock-adapter library, as well as native Jest/Vitest
mocks and AbortController.
Using
axios-mock-adapter
axios-mock-adapter is one of the most straightforward
utilities for intercepting Axios requests during unit and integration
tests. It provides built-in helper methods specifically designed to
simulate network failures.
1. Mocking Network Timeouts
Axios requests can time out if the remote server takes longer to
respond than the configured timeout property. To test how
your error handling catches an ECONNABORTED error code:
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
describe('Axios Timeout Handling', () => {
let mock;
beforeEach(() => {
mock = new MockAdapter(axios);
});
afterEach(() => {
mock.restore();
});
it('handles a timed-out request', async () => {
// Mock the endpoint to trigger a timeout
mock.onGet('/api/data').timeout();
try {
await axios.get('/api/data', { timeout: 1000 });
} catch (error) {
expect(error.code).toBe('ECONNABORTED');
expect(error.message).toContain('timeout');
}
});
});2. Mocking Dropped Connections and Network Errors
When a client loses internet connectivity or the connection is
abruptly closed by the server before a response is sent, Axios throws a
network error (typically with code ERR_NETWORK).
You can simulate a dropped connection using
.networkError():
it('handles a dropped network connection', async () => {
// Mock the endpoint to fail with a network error
mock.onGet('/api/data').networkError();
try {
await axios.get('/api/data');
} catch (error) {
expect(error.isAxiosError).toBe(true);
expect(error.message).toBe('Network Error');
expect(error.response).toBeUndefined();
}
});Mocking with Jest / Vitest Spies
If you prefer not to install an extra adapter library, you can
directly mock axios.get or axios.request using
Jest or Vitest to reject with simulated network errors.
Simulating a Timeout Error
import axios, { AxiosError } from 'axios';
jest.mock('axios');
it('handles timeout error using standard mock', async () => {
const timeoutError = new AxiosError(
'timeout of 1000ms exceeded',
'ECONNABORTED'
);
axios.get.mockRejectedValueOnce(timeoutError);
await expect(axios.get('/api/data')).rejects.toMatchObject({
code: 'ECONNABORTED',
});
});Simulating a Dropped Connection Error
it('handles dropped connection using standard mock', async () => {
const networkError = new AxiosError(
'Network Error',
'ERR_NETWORK'
);
axios.get.mockRejectedValueOnce(networkError);
await expect(axios.get('/api/data')).rejects.toMatchObject({
code: 'ERR_NETWORK',
message: 'Network Error',
});
});Simulating
Aborted Requests with AbortController
In modern applications, dropped or canceled requests are often
triggered programmatically via an AbortController. You can
simulate client-side aborts directly in your tests:
it('cancels the request using AbortController', async () => {
const controller = new AbortController();
// Abort the connection immediately
controller.abort();
try {
await axios.get('/api/data', {
signal: controller.signal,
});
} catch (error) {
expect(axios.isCancel(error)).toBe(true);
expect(error.code).toBe('ERR_CANCELED');
}
});Summary Checklist for Axios Error Assertions
When testing resilience against network instability, verify the
following properties in your catch blocks:
- Timeouts (
.timeout()): Expecterror.code === 'ECONNABORTED'and an undefinederror.response. - Dropped Connections (
.networkError()): Expecterror.code === 'ERR_NETWORK',error.message === 'Network Error', anderror.response === undefined. - Client Cancellations: Expect
axios.isCancel(error) === trueanderror.code === 'ERR_CANCELED'.