diff --git a/src/handle_request.js b/src/handle_request.js index 99fd3c7..d14703a 100644 --- a/src/handle_request.js +++ b/src/handle_request.js @@ -60,6 +60,10 @@ function handleRequest(mockAdapter, resolve, reject, config) { utils.purgeIfReplyOnce(mockAdapter, handler); } + if (handler[0] instanceof RegExp) { + config.urlParams = utils.getURLParams(handler[0], url, config.baseURL); + } + if (handler.length === 2) { // passThrough handler mockAdapter.originalAdapter(config).then(resolve, reject); diff --git a/src/utils.js b/src/utils.js index 5be88d0..2420de8 100644 --- a/src/utils.js +++ b/src/utils.js @@ -103,6 +103,11 @@ function isBodyMatching(body, requiredBody) { return isObjectMatching(parsedBody ? parsedBody : body, requiredBody); } +function getURLParams(matcher, url, baseURL) { + var matchResult = baseURL ? combineUrls(baseURL, url).match(matcher) : url.match(matcher); + return matchResult.groups || {}; +} + function purgeIfReplyOnce(mock, handler) { Object.keys(mock.handlers).forEach(function (key) { var index = mock.handlers[key].indexOf(handler); @@ -190,6 +195,7 @@ function createCouldNotFindMockError(config) { module.exports = { find: find, findHandler: findHandler, + getURLParams: getURLParams, purgeIfReplyOnce: purgeIfReplyOnce, settle: settle, isStream: isStream, diff --git a/test/basics.spec.js b/test/basics.spec.js index 9976cc6..eeaa757 100644 --- a/test/basics.spec.js +++ b/test/basics.spec.js @@ -123,6 +123,17 @@ describe("MockAdapter basics", function () { }); }); + it("supports capture groups in urls with a regex", function () { + mock.onGet(/\/api\/foo\/(?[^/]+)\/bar\/(?[^?/]+)$/).reply(function (config) { + return [200, config.urlParams]; + }); + + return instance.get("/api/foo/1/bar/2").then(function (response) { + expect(response.data.fooId).to.equal('1'); + expect(response.data.barId).to.equal('2'); + }); + }); + it("can pass query params for get to match to a handler", function () { mock .onGet("/withParams", { params: { foo: "bar", bar: "foo" } })