JSPM

  • Created
  • Published
  • Downloads 1738332
  • Score
    100M100P100Q210869F
  • License MIT

Axios adapter that allows to easily mock requests

Package Exports

  • axios-mock-adapter

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (axios-mock-adapter) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

axios-mock-adapter

Build Status devDependency Status

Axios adapter that allows to easily mock requests

Installation

Using npm:

$ npm install axios-mock-adapter

Example

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);
// which is the same as:
//   var mock = new MockAdapter();
//   axios.defaults.adapter = mock.adapter();

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

axios.get('/users')
  .then(function(response) {
    console.log(response.data);
  });

// If a request is made for a URL that is not handled in the mock adapter,
// the promise will reject with a response that has status 404.

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' }
    ]
  }];
});

Using a regex

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

  return [200, {}];
});

Mocking any request to a given url

// mocks GET, POST, ... requests to /foo
mock.onAny('/foo').reply(200);

.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]
];

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, {}];
});