How are multiple handler matches supposed to behave? #965
-
QuestionI'm using msw-storybook-addon in a react project and a backend I don't control doesn't do routing the normal way, it does routing via a MSW Environment
Example setup// in my story
Base.parameters = {
msw: [
rest.get(process.env.REACT_APP_BACKEND_URL, (req, res, ctx) => {
const route = req.url.searchParams.get("route");
if (route === "some-first-route") {
return res(ctx.json({ responseFor: 'first-route' }));
} else {
return;
}
}),
rest.get(process.env.REACT_APP_BACKEND_URL, (req, res, ctx) => {
const route = req.url.searchParams.get("route");
if (route === "some-second-route") {
return res(ctx.json({ responseFor: 'second-route' }));
} else {
return;
}
})
]
} Example requestawait axios.get(`/?route=${useFirstRoute ? 'some-first-route' : 'some-second-route'}`) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hey, @RyanClementsHax. Thank you for raising this! We do have the Request matching section but it indeed misses to mention how the library handles the request handler lookup and what will happen when a request matches multiple handlers.
This behavior is not an incident, it was always intended. Allow me to clarify it below.
Lines 50 to 54 in f6fbd6c
rest.get(process.env.REACT_APP_BACKEND_URL, (req, res, ctx) => {
const route = req.url.searchParams.get('route')
switch (route) {
case 'first-route': {
return res(ctx.text('first'))
}
case 'second-route': {
return res(ctx.text('second'))
}
default:
return res(ctx.status(404))
}
})
// List this handler first, so that "/user/me" doesn't match "/user/:id"
// where "me" would be considered the value of the "id" parameter.
rest.get('/user/me', (req, res, ctx) => {
return res(...)
})
// Handle other, intended requests.
rest.get('/user/:id', (req, res, ctx) => {
return res(...)
}) With that being said, I recommend you rewrite your handler and put any logic that affects the response in that handler. In the end, collocating logic with the handlers (resources) will make your mocks more evident and easier to browse through. |
Beta Was this translation helpful? Give feedback.
Hey, @RyanClementsHax. Thank you for raising this!
We do have the Request matching section but it indeed misses to mention how the library handles the request handler lookup and what will happen when a request matches multiple handlers.
This behavior is not an incident, it was always intended. Allow me to clarify it below.
msw/src/utils/getResponse.ts
Lines 50 to 54 in f6fbd6c