What is axios-mock-adapter?
axios-mock-adapter is a package for mocking Axios requests for testing purposes. It allows developers to simulate server responses, test error handling, and ensure that the front-end behaves as expected without the need for an actual backend during the development and testing phases.
What are axios-mock-adapter's main functionalities?
Mocking GET requests
This feature allows you to mock a GET request to a specific URL and provide a fake response that the axios call will receive.
const MockAdapter = require('axios-mock-adapter');
const axios = require('axios');
const mock = new MockAdapter(axios);
mock.onGet('/users').reply(200, [
{ id: 1, name: 'John Smith' }
]);
Mocking POST requests
This feature allows you to mock a POST request to a specific URL and provide a fake response, which can be used to simulate form submissions or other POST operations.
const MockAdapter = require('axios-mock-adapter');
const axios = require('axios');
const mock = new MockAdapter(axios);
mock.onPost('/login').reply(200, {
user: 'admin',
token: 'fake-token'
});
Simulating network errors
This feature allows you to simulate network errors to test how your application handles them.
const MockAdapter = require('axios-mock-adapter');
const axios = require('axios');
const mock = new MockAdapter(axios);
mock.onGet('/unreachable').networkError();
Delaying responses
This feature allows you to delay the mock response, which can be useful for testing loading states and asynchronous operations.
const MockAdapter = require('axios-mock-adapter');
const axios = require('axios');
const mock = new MockAdapter(axios);
mock.onGet('/users').reply(function() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve([200, [{ id: 1, name: 'John Smith' }]]);
}, 1000);
});
});
Specifying request parameters
This feature allows you to specify request parameters for the mock, so you can test how your application handles different query strings or request configurations.
const MockAdapter = require('axios-mock-adapter');
const axios = require('axios');
const mock = new MockAdapter(axios);
mock.onGet('/users', { params: { search: 'John' } }).reply(200, [
{ id: 1, name: 'John Smith' }
]);
Other packages similar to axios-mock-adapter
nock
nock is a powerful HTTP server mocking and expectations library for Node.js. It allows you to intercept HTTP requests and provide predefined responses. Compared to axios-mock-adapter, nock works at a lower level, intercepting HTTP requests at the Node.js level, which means it can mock requests made by any HTTP client, not just Axios.
jest-mock-axios
jest-mock-axios is a mock for Axios specifically designed to work with Jest testing framework. It provides a set of utilities for mocking Axios instances, tracking requests, and asserting on response data. It is similar to axios-mock-adapter but is more tightly integrated with Jest, making it a good choice for projects that use Jest for testing.
sinon
sinon is a standalone test spies, stubs, and mocks library for JavaScript. While not limited to HTTP requests, sinon can be used to mock Axios or any other library by replacing the actual functions with stubs that can be controlled and inspected. It is more general-purpose compared to axios-mock-adapter, which is focused solely on mocking Axios requests.
axios-mock-adapter
Axios adapter that allows to easily mock requests
Installation
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.
Example
Mocking a GET
request
var axios = require('axios');
var MockAdapter = require('axios-mock-adapter');
var mock = new MockAdapter(axios);
mock.onGet('/users').reply(200, {
users: [
{ id: 1, name: 'John Smith' }
]
});
axios.get('/users')
.then(function(response) {
console.log(response.data);
});
To add a delay to responses, specify a delay ammount (in milliseconds) when instantiating the adapter
var mock = new MockAdapter(axiosInstance, { delayResponse: 2000 });
You can restore the original adapter (which will remove the mocking behavior)
mock.restore();
You can also reset the registered mock handlers with reset
mock.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.
Passing a function to reply
mock.onGet('/users').reply(function(config) {
return [200, {
users: [
{ id: 1, name: 'John Smith' }
]
}];
});
Using a regex
mock.onGet(/\/users\/\d+/).reply(function(config) {
return [200, {}];
});
Chaining is also supported
mock
.onGet('/users').reply(200, users)
.onGet('/posts').reply(200, posts);
.replyOnce()
can be used to let the mock only reply once
mock
.onGet('/users').replyOnce(200, users)
.onGet('/users').replyOnce(500);
Mocking any request to a given url
mock.onAny('/foo').reply(200);
.onAny
can be useful when you want to test for a specific order of requests
const responses = [
['GET', '/foo', 200, { foo: 'bar' }],
['POST', '/bar', 200],
['PUT', '/baz', 200]
];
mock.onAny(/.*/).reply(config => {
const [method, url, ...response] = responses.shift();
if (config.url === url && config.method.toUpperCase() === method) return response;
return [500, {}];
});
Mocking a request with a specific request body/data
mock.onPut('/withBody', { request: 'body' }).reply(200);