Skip to content

Commit

Permalink
Fix: support overwriting routes with regex matcher
Browse files Browse the repository at this point in the history
Prior to this change, using a regex matcher combined with
`overwriteRoutes: true` would not overwrite the route. This is because
the inspection was comparing regexes with `===` which will always return
`false`. To fix this, object identifiers are coerced to strings before
comparing. Function matchers are not affected by this change.
  • Loading branch information
Adam Gruber authored and wheresrhys committed Oct 30, 2020
1 parent 99ef594 commit 3d12042
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
12 changes: 7 additions & 5 deletions src/lib/set-up-and-tear-down.js
Expand Up @@ -13,11 +13,13 @@ FetchMock.mock = function (...args) {
FetchMock.addRoute = function (uncompiledRoute) {
debug('Adding route', uncompiledRoute);
const route = this.compileRoute(uncompiledRoute);
const clashes = this.routes.filter(
({ identifier, method }) =>
identifier === route.identifier &&
(!method || !route.method || method === route.method)
);
const clashes = this.routes.filter(({ identifier, method }) => {
const isMatch =
typeof identifier === 'function'
? identifier === route.identifier
: String(identifier) === String(route.identifier);
return isMatch && (!method || !route.method || method === route.method);
});

if (this.getOption('overwriteRoutes', route) === false || !clashes.length) {
this._uncompiledRoutes.push(uncompiledRoute);
Expand Down
8 changes: 8 additions & 0 deletions test/specs/config/overwriteRoutes.test.js
Expand Up @@ -24,6 +24,14 @@ describe('overwriteRoutes', () => {
expect(res.status).to.equal(300);
});

it('allow overwriting existing route, regex matcher', async () => {
fm.config.overwriteRoutes = true;
expect(() => fm.mock(/a\.com/, 200).mock(/a\.com/, 300)).not.to.throw();

const res = await fm.fetchHandler('http://a.com');
expect(res.status).to.equal(300);
});

it('allow adding additional routes with same matcher', async () => {
fm.config.overwriteRoutes = false;
expect(() =>
Expand Down

0 comments on commit 3d12042

Please sign in to comment.