axios-mock-adapter-path-params
Forked from ctimmerm's package axios-mock-adapter with kierate's pull request merged into it.
Axios adapter that allows to easily mock requests
Installation
Using npm:
$ npm install axios-mock-adapter-path-params --save-dev
Using yarn:
$ yarn add axios-mock-adapter-path-params
axios-mock-adapter-path-params 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 = ;var MockAdapter = ; // This sets the mock adapter on the default instancevar mock = axios; // Mock any GET request to /users// arguments for reply are (status, data, headers)mock; axios;
Mocking a GET
request with specific parameters
var axios = ;var MockAdapter = ; // This sets the mock adapter on the default instancevar mock = axios; // Mock GET request to /users when param `searchText` is 'John'// arguments for reply are (status, data, headers)mock; axios ;
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 = axiosInstance delayResponse: 2000 ;
You can restore the original adapter (which will remove the mocking behavior)
mock;
You can also reset the registered mock handlers with resetHandlers
mock;
You can reset both registered mock handlers and history items with reset
mock;
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; // networkErrorOnce can be used to mock a network error only oncemock;
Mock a network timeout
// Returns a failed promise with Error with code set to 'ECONNABORTED'mock; // timeoutOnce can be used to mock a timeout only oncemock;
Passing a function to reply
mock;
Passing a function to reply
that returns an axios request, essentially mocking a redirect
mock;
Using a regex
mock;
Using variables in regex
const usersUri = "/users";const url = `/*`; mock;
Using route params (colon notation)
const routeParams = ":userId": "[0-9]{1,8}" ":filter": "active|inactive|all";const mock = axios {} routeParams; mock; axios;
Using route params (curly braces notation)
const routeParams = "{uuid}": "[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}" "{page}": "\\d?";const mock = axios {} routeParams; mock; axios;
Specify no path to match by verb alone
// Reject all POST requests with HTTP 500mock;
Chaining is also supported
mock;
.replyOnce()
can be used to let the mock only reply once
mock // After the first request to /users, this handler is removed ; // 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 /foomock;
.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 requestsmock;
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 500mock;
Mocking a request with a specific request body/data
mock;
Using an asymmetric matcher, for example Jest matchers
mock ;
Using a custom asymmetric matcher (any object that has a asymmetricMatch
property)
mock ;
.passThrough()
forwards the matched request over network
// Mock POST requests to /api with HTTP 201, but forward// GET requests to servermock ;
Recall that the order of handlers is significant
// Mock specific requests, but let unmatched ones throughmock ;
Note that passThrough
requests are not subject to delaying by delayResponse
.
If you set onNoMatch
option to passthrough
all requests would be forwarded over network by default
// Mock all requests to /foo with HTTP 200, but forward// any others requests to servervar mock = axiosInstance onNoMatch: "passthrough" ; mock;
Using onNoMatch
option with throwException
to throw an exception when a request is made without match any handler. It's helpful to debug your test mocks.
var mock = axiosInstance onNoMatch: "throwException" ; mock; axios; // Exception message on console://// Could not find mock for:// {// "method": "get",// "url": "http://localhost/unexistent-path"// }
As of 1.7.0, reply
function may return a Promise:
mock;
Composing from multiple sources with Promises:
var normalAxios = axios;var mockAxios = axios;var mock = mockAxios; mock ;
History
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.
;
You can clear the history with resetHistory
mock;