How to Mock Axios ECONNREFUSED Network Errors

Testing how an application handles connection failures is essential for building resilient systems. When a server is offline or unreachable, Axios throws a network error typically identified by the ECONNREFUSED error code in Node.js environments. This guide explains how to mock these network-level connection refused errors using standard testing tools like axios-mock-adapter, Jest, and Mock Service Worker (MSW), enabling you to verify your application's error handling and retry logic without needing a live, failing backend.


Understanding the ECONNREFUSED Error in Axios

When a connection is refused, Axios does not receive an HTTP response. Consequently, the resulting error object does not contain a response property, but it contains:


Method 1: Using axios-mock-adapter

axios-mock-adapter is one of the most widely used libraries for mocking Axios requests. It provides built-in methods to simulate network errors.

1. Basic Network Error

The .networkError() helper simulates a low-level network failure:

import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import { fetchData } from './apiService';

describe('fetchData error handling', () => {
  let mock;

  beforeEach(() => {
    mock = new MockAdapter(axios);
  });

  afterEach(() => {
    mock.restore();
  });

  it('should handle network errors', async () => {
    mock.onGet('/users').networkError();

    await expect(fetchData()).rejects.toThrow('Network Error');
  });
});

2. Explicit ECONNREFUSED Error

If your application specifically checks for error.code === 'ECONNREFUSED', you can reject with a custom error object:

it('should handle explicit ECONNREFUSED errors', async () => {
  const connectionRefusedError = Object.assign(
    new Error('connect ECONNREFUSED 127.0.0.1:3000'),
    {
      code: 'ECONNREFUSED',
      isAxiosError: true,
      config: {}
    }
  );

  mock.onGet('/users').reply(() => Promise.reject(connectionRefusedError));

  try {
    await fetchData();
  } catch (error) {
    expect(error.code).toBe('ECONNREFUSED');
  }
});

Method 2: Using Native Jest Mocks

If you prefer not to use third-party adapter libraries, you can mock Axios directly using Jest.

import axios from 'axios';
import { fetchData } from './apiService';

jest.mock('axios');

describe('fetchData with Jest mock', () => {
  it('rejects with ECONNREFUSED', async () => {
    const error = new Error('connect ECONNREFUSED 127.0.0.1:3000');
    error.code = 'ECONNREFUSED';
    error.isAxiosError = true;

    axios.get.mockRejectedValueOnce(error);

    await expect(fetchData()).rejects.toMatchObject({
      code: 'ECONNREFUSED'
    });
  });
});

Method 3: Using Mock Service Worker (MSW)

MSW intercepts requests at the network layer, providing realistic failure simulations for both Node.js and browser environments.

import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
import { fetchData } from './apiService';

const server = setupServer(
  http.get('https://api.example.com/users', () => {
    return HttpResponse.error(); // Simulates a network failure
  })
);

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

test('handles network failure', async () => {
  await expect(fetchData()).rejects.toThrow();
});

Best Practices for Testing Connection Failures

  1. Verify Fallback Mechanisms: Ensure your UI or service displays a proper error message or fallback state when ECONNREFUSED is encountered.
  2. Test Retry Policies: If your client uses libraries like axios-retry, use .networkErrorOnce() to test that the request retries and eventually succeeds.
  3. Assert Cleanup: Always reset or restore mocks after each test to prevent side effects across test suites.