Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(matchMock): handle regex mock paths directly #281

Merged
merged 2 commits into from
Dec 3, 2024
Merged
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
16 changes: 16 additions & 0 deletions packages/parrot-core/__tests__/utils/matchMock.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,22 @@ describe('matchMock', () => {
expect(matchMock(req, {}, mocks)).toEqual(mocks[0]);
});

it('matches mock object when path variable', () => {
const mocks = [
{ request: { path: '/squawk/:id', headers: 'ahoy', 'Keep-Alive': 'timeout=5' } },
];
const req = { path: '/squawk/123', headers: 'ahoy', 'Keep-Alive': 'timeout=5' };
expect(matchMock(req, {}, mocks)).toEqual(mocks[0]);
});

it('matches mock object when regex path', () => {
const mocks = [
{ request: { path: /^\/squawk\/\d?/, headers: 'ahoy', 'Keep-Alive': 'timeout=5' } },
];
const req = { path: '/squawk/123', headers: 'ahoy', 'Keep-Alive': 'timeout=5' };
expect(matchMock(req, {}, mocks)).toEqual(mocks[0]);
});

it('throws when mocks is not an array', () => {
const mocks = {};
expect(() => matchMock({}, {}, mocks)).toThrow(
Expand Down
3 changes: 3 additions & 0 deletions packages/parrot-core/src/utils/matchMock.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ function matchRequest(normalizedRequest) {
return request =>
Object.keys(request).every(property => {
if (property === 'path') {
if (request.path instanceof RegExp) {
return request.path.test(normalizedRequest.path);
}
const matchRoute = match(request.path);
const result = matchRoute(normalizedRequest.path);
return result !== false;
Expand Down
Loading