axios-json-mock
Axios helper that allows to easily mock request
Installation
Using npm:
npm install axios-json-mock --save
axios-json-mock works on Node as well as in a browser, it works with axios v0.16.0 and above.
Example
Mocking a GET
request
import axios from 'axios';
import AxiosJsonMock from 'axios-json-mock';
const instance = new AxiosJsonMock(axios);
const responseWith = {
200: [
{ id: 23, name: 'John Lennon' }
],
400: {
message: 'Bad Request'
}
}
instance({ url: '/users' }, {
useMock: true,
responseWith
})
.then(response => console.log(response.data))
Add a specify status code
instance({ url: '/users' }, {
useMock: true,
statusCode: 400,
responseWith
})
.catch(response => console.error(response))
To add a delay to responses, specify amout (in milliseconds)
const instance = new AxiosJsonMock(axios, { timeout: 1000 });
Using a mocks folder with json files
├── __dirname
│ ├── __mocks__
│ │ ├── userlist.json
│ │ ├── *.json
│ │ ├── *.json
userlist.json
{
"200": [
{ "id": 23, "name": "John Lennon" }
],
"400": {
"message": "Bad Request"
}
}
import axios from 'axios';
import AxiosJsonMock from 'axios-json-mock';
const instance = new AxiosJsonMock(axios, { mockFolder: __dirname + '__mocks__' });
instance({ url: '/users' }, {
useMock: true,
mockName: 'userlist'
})
.then(response => console.log(response.data))
Turn off mocks and make real request
instance({ url: '/users' }, {
useMock: false,
mockName: 'userlist'
})
.then(response => console.log(response.data))