axios-mock-adapter icon indicating copy to clipboard operation
axios-mock-adapter copied to clipboard

Allow function matcher

Open flaviojs opened this issue 7 years ago • 0 comments

I have a GET request with the url in the following format: api/v1/rest/collection?startDate>="(ISO 8601 string)"&startDate<"(ISO 8601 string)"

I want to let it pass through (to a default baseURL) when the startDate range is outside the specific range I am mocking.

The simplest way to enable this is by allowing a matcher function as an argument to onXXX methods. To support other complex mocking scenarios it could receive the (mutable) config object that the reply function also receives.

This is how I would use it:

var axios = require('axios')
var AxiosMockAdapter = require('axios-mock-adapter')

axios.default.defaults.baseURL = 'http://url.to.test.api'
var mock = new AxiosMockAdapter(axios, {
  delayResponse: 100 // ms
})

var data = [] // mocked data ordered by startDate
mock.onGet(function (config) {
  var start // parse "startDate>=..." from query of config.url
  var end // parse "startDate<..." from query of config.url
  if (config.url.indexOf('api/v1/rest/collection?') === 0 && data[0].startDate <= start && data[data.length-1].startDate >= end) {
    config.start = start
    config.end = end
    return true
  }
  return false
}).reply(function (config) {
  console.log('mock ' + config.url)
  return [200, data.filter(x => x.startDate >= config.start && x.startDate < config.end)]
})

mock.onAny().passThrough()

flaviojs avatar Mar 19 '18 16:03 flaviojs