Conditional request handlers #1572
Replies: 3 comments 2 replies
-
Hi, @RobinClowers. You can create a handler that would only match on a custom predicate by handling an intercepted request conditionally in a more permissive standard request handler. For example, here's how you could handle a request differently based on its body: import { rest } from 'msw'
export const handlers = [
rest.post('/endpoint', (req, res, ctx) => {
const requestBody = req.body
if (typeof requestBody === 'object' && requestBody.query.includes('GetUser') {
// Respond with a mocked GraphQL response in this case.
return res(ctx.json({ data: { user: { id: 1 } }))
}
// Otherwise, perform the request as-is.
return req.passthrough()
})
] Note that returning We are mentioning this pattern in the Conditional response resolver section of the docs. Let me know if this achieves what you want. |
Beta Was this translation helpful? Give feedback.
-
Thanks for getting back to me! I'm confused, the docs you linked say:
In my tests I have code like this: beforeEach(() => {
server.use(fooHandler);
server.use(barHandler);
}); In my test, I should be doing one query that is handled by each of the handlers, but by adding logs, I can see that the
|
Beta Was this translation helpful? Give feedback.
-
I noticed this is incorrect. Returning |
Beta Was this translation helpful? Give feedback.
-
I have an API that's sort of similar to graphql, I'm always POSTing to the same endpoint with different bodies. I would like to be able register handlers that only match based on a predicate, but I don't see any way to do that. I tried using
request.passthrough
, but that doesn't seem to attempt to match other handlers. Do I have to create my own custom handler derived fromRequestHandler
?Beta Was this translation helpful? Give feedback.
All reactions