Skip to content

Commit

Permalink
feat: match URL params by path-to-regexp
Browse files Browse the repository at this point in the history
  • Loading branch information
tenorok committed Jun 14, 2022
1 parent b8698c3 commit 56fc6d1
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/utils/faker.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,16 @@ export class Faker {
};

matchMock = (url, method = 'GET') => {
const { path } = getNormalizedUrl(url);
const { fullUrl } = getNormalizedUrl(url);

for (let key in this.requestMap) {
const { url: requestUrl, method: requestMethod } =
this.requestMap[key];
const { path: requestPath } =
const { fullUrlEscaped } =
getNormalizedUrl(requestUrl);

if (
match(requestPath)(path) &&
match(fullUrlEscaped)(fullUrl) &&
method == requestMethod &&
!this.requestMap[key].skip
) {
Expand Down
13 changes: 13 additions & 0 deletions src/utils/faker.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@ describe('Faker', () => {
response: {},
delay: 0,
},
{
url: 'http://request.com?a=1&b=2',
method: 'GET',
status: 200,
response: {},
delay: 0,
},
];
faker.makeInitialRequestMap(requests);

Expand All @@ -84,6 +91,12 @@ describe('Faker', () => {
expect(actual.method).toEqual(requests[2].method);
expect(actual.skip).toEqual(false);
});
it('should return request if url matches with the query parameters', () => {
const actual = faker.matchMock('http://request.com?a=1&b=2', 'GET');
expect(actual.url).toEqual(requests[3].url);
expect(actual.method).toEqual(requests[3].method);
expect(actual.skip).toEqual(false);
});
});

describe('restore', () => {
Expand Down
5 changes: 5 additions & 0 deletions src/utils/url.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,13 @@ export const getNormalizedUrl = (rawUrl = '') => {
searchParamKeys.push(key);
}
}

const searchEscaped = url.search ? '\\' + url.search : '';

return {
path: url.host + url.pathname,
searchParamKeys,
fullUrl: url.host + url.pathname + url.search,
fullUrlEscaped: url.host + url.pathname + searchEscaped,
};
};

0 comments on commit 56fc6d1

Please sign in to comment.