Skip to content

Commit

Permalink
feat(msw): allow regex for entire paths instead of only property names (
Browse files Browse the repository at this point in the history
  • Loading branch information
GMierzwa committed Oct 11, 2023
1 parent 1899009 commit 9a4ce8f
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
8 changes: 5 additions & 3 deletions docs/src/pages/reference/configuration/output.md
Original file line number Diff line number Diff line change
Expand Up @@ -681,7 +681,7 @@ Give you the possibility to override the generated mock

Type: `Object` or `Function`.

You can use this to override the generated mock per property. Properties can take a function who take the specification in argument and should return un object or directly the object. Each key of this object can be a regex or directly the name of the property to override and the value can be a function which return the wanted value or directly the value. If you use a function this will be executed at runtime.
You can use this to override the generated mock per property. Properties can take a function who take the specification in argument and should return un object or directly the object. Each key of this object can be a regex or directly the path of the property to override and the value can be a function which return the wanted value or directly the value. If you use a function this will be executed at runtime.

```js
module.exports = {
Expand All @@ -690,8 +690,10 @@ module.exports = {
override: {
mock: {
properties: {
'/tag|name/': 'jon',
email: () => faker.internet.email(),
'/tag|name/': 'jon', // Matches every property named 'tag' or 'name', including nested ones
'/.*\.user\.id/': faker.string.uuid(), // Matches every property named 'id', inside an object named 'user', including nested ones
email: () => faker.internet.email(), // Matches only the property 'email'
'user.id': () => faker.string.uuid(), // Matches only the full path 'user.id'
},
},
},
Expand Down
5 changes: 3 additions & 2 deletions packages/msw/src/resolvers/value.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,16 @@ export const resolveMockOverride = (
properties: Record<string, string> | undefined = {},
item: SchemaObject & { name: string; path?: string },
) => {
const path = item.path ? item.path : `#.${item.name}`;
const property = Object.entries(properties).find(([key]) => {
if (isRegex(key)) {
const regex = new RegExp(key.slice(1, key.length - 1));
if (regex.test(item.name)) {
if (regex.test(item.name) || regex.test(path)) {
return true;
}
}

if (`#.${key}` === (item.path ? item.path : `#.${item.name}`)) {
if (`#.${key}` === path) {
return true;
}

Expand Down

1 comment on commit 9a4ce8f

@vercel
Copy link

@vercel vercel bot commented on 9a4ce8f Oct 11, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.