Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/handle_request.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
6 changes: 6 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -190,6 +195,7 @@ function createCouldNotFindMockError(config) {
module.exports = {
find: find,
findHandler: findHandler,
getURLParams: getURLParams,
purgeIfReplyOnce: purgeIfReplyOnce,
settle: settle,
isStream: isStream,
Expand Down
11 changes: 11 additions & 0 deletions test/basics.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,17 @@ describe("MockAdapter basics", function () {
});
});

it("supports capture groups in urls with a regex", function () {
mock.onGet(/\/api\/foo\/(?<fooId>[^/]+)\/bar\/(?<barId>[^?/]+)$/).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" } })
Expand Down