4

How to mock http request with route params?

var axios = require('axios');
var MockAdapter = require('axios-mock-adapter');

// This sets the mock adapter on the default instance
var mock = new MockAdapter(axios);
mock.onGet('/api/colleges/:collegeId/branches/:branchesId').reply(200);

1 Answers1

2

Convert your placeholders to wildcards and the path to a RegExp:

function route (path = '') {
  return typeof path === 'string'
    ? new RegExp(path.replace(/:\w+/g, '[^/]+'))
    : path
}

Use like this:

mock.onGet(route('/api/colleges/:collegeId/branches/:branchesId')).reply(200);
Dave Stewart
  • 2,324
  • 2
  • 22
  • 24