Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including axios-mock-adapter with all npm packages installed. Try it out:

require("axios/package.json"); // axios is a peer dependency. var axiosMockAdapter = require("axios-mock-adapter")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

axios-mock-adapter v1.16.0

Axios adapter that allows to easily mock requests


Build Status devDependency Status

Axios adapter that allows to easily mock requests


Using npm:

$ npm install axios-mock-adapter --save-dev

It's also available as a UMD build:


axios-mock-adapter works on Node as well as in a browser, it works with axios v0.9.0 and above.


Mocking a GET request

var axios = require('axios');
var MockAdapter = require('axios-mock-adapter');

// This sets the mock adapter on the default instance
var mock = new MockAdapter(axios);

// Mock any GET request to /users
// arguments for reply are (status, data, headers)
mock.onGet('/users').reply(200, {
  users: [
    { id: 1, name: 'John Smith' }

  .then(function(response) {

Mocking a GET request with specific parameters

var axios = require('axios');
var MockAdapter = require('axios-mock-adapter');

// This sets the mock adapter on the default instance
var mock = new MockAdapter(axios);

// Mock GET request to /users when param `searchText` is 'John'
// arguments for reply are (status, data, headers)
mock.onGet('/users', { params: { searchText: 'John' } }).reply(200, {
  users: [
    { id: 1, name: 'John Smith' }

axios.get('/users', { params: { searchText: 'John' } } )
  .then(function(response) {

To add a delay to responses, specify a delay amount (in milliseconds) when instantiating the adapter

// All requests using this instance will have a 2 seconds delay:
var mock = new MockAdapter(axiosInstance, { delayResponse: 2000 });

You can restore the original adapter (which will remove the mocking behavior)


You can also reset the registered mock handlers with reset


reset is different from restore in that restore removes the mocking from the axios instance completely, whereas reset only removes all mock handlers that were added with onGet, onPost, etc. but leaves the mocking in place.

Mock a low level network error

// Returns a failed promise with Error('Network Error');

Mock a network timeout

// Returns a failed promise with Error with code set to 'ECONNABORTED'

Passing a function to reply

mock.onGet('/users').reply(function(config) {
  // `config` is the axios config and contains things like the url

  // return an array in the form of [status, data, headers]
  return [200, {
    users: [
      { id: 1, name: 'John Smith' }

Passing a function to reply that returns an axios request, essentially mocking a redirect

mock.onPost('/foo').reply(function(config) {
  return axios.get('/bar');

Using a regex

mock.onGet(/\/users\/\d+/).reply(function(config) {
  // the actual id can be grabbed from config.url

  return [200, {}];

Using variables in regex

const usersUri = '/users';
const url = new RegExp(`${usersUri}/*`);

mock.onGet(url).reply(200, users);

Specify no path to match by verb alone

// Reject all POST requests with HTTP 500

Chaining is also supported

  .onGet('/users').reply(200, users)
  .onGet('/posts').reply(200, posts);

.replyOnce() can be used to let the mock only reply once

  .onGet('/users').replyOnce(200, users) // After the first request to /users, this handler is removed
  .onGet('/users').replyOnce(500);       // The second request to /users will have status code 500
                                         // Any following request would return a 404 since there are
                                         // no matching handlers left

Mocking any request to a given url

// mocks GET, POST, ... requests to /foo

.onAny can be useful when you want to test for a specific order of requests

// Expected order of requests:
const responses = [
  ['GET',  '/foo', 200, { foo: 'bar' }],
  ['POST', '/bar', 200],
  ['PUT',  '/baz', 200]

// Match ALL requests
mock.onAny().reply(config => {
  const [method, url, ...response] = responses.shift();
  if (config.url === url && config.method.toUpperCase() === method) return response;
  // Unexpected request, error out
  return [500, {}];

Requests that do not map to a mock handler are rejected with a HTTP 404 response. Since handlers are matched in order, a final onAny() can be used to change the default behaviour

 // Mock GET requests to /foo, reject all others with HTTP 500

Mocking a request with a specific request body/data

mock.onPut('/product', { id: 4, name: 'foo' }).reply(204);

.passThrough() forwards the matched request over network

// Mock POST requests to /api with HTTP 201, but forward
// GET requests to server

Recall that the order of handlers is significant

// Mock specific requests, but let unmatched ones through
  .onPut('/bar', { xyz: 'abc' }).reply(204)

Note that passThrough requests are not subject to delaying by delayResponse.

As of 1.7.0, reply function may return a Promise:

mock.onGet('/product').reply(function(config) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      if (Math.random() > 0.1) {
        resolve([200, { id: 4, name: 'foo' } ]);
      } else {
        // reject() reason will be passed as-is.
        // Use HTTP error status code to simulate server failure.
        resolve([500, { success: false } ]);
    }, 1000);

Composing from multiple sources with Promises:

var normalAxios = axios.create();
var mockAxios = axios.create();
var mock = new MockAdapter(mockAxios);

  .reply(() => Promise.all([
        .then(resp =>,
        .then(resp =>,
      { id: '-1', content: 'extra row 1' },
      { id: '-2', content: 'extra row 2' }
      sources => [200, sources.reduce((agg, source) => agg.concat(source))]


The history property allows you to enumerate existing axios request objects. The property is an object of verb keys referencing arrays of request objects.

This is useful for testing.

describe('Feature', () => {
  it('requests an endpoint', (done) => {
    var mock = new AxiosMockAdapter(axios);

      .then(() => {
        expect([0].data).toBe(JSON.stringify({ foo: 'bar' }));
RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free