Is your feature request related to a problem? Please describe.
When writing tests, I would like to ensure that no external calls are made. If a request is made and there is no matching path handler registered in msw, I would like to handle the request and throw an error so that the test fails.
Describe the solution you'd like
I'd like a fallback handler that would allow me to handle unmatched requests. Maybe something like this?
import { rest, setupWorker } from 'msw';
export const worker = setupWorker(
rest.fallback((req, res, ctx) => {
throw new Error(`No matching path found for ${req.url}`);
});
);
I would probably only register this handler in the test environment. Otherwise, I'd probably use the default fallback, and let the request go to the actual server.
Describe alternatives you've considered
I believe I could implement this with a path of *, but I would have to add multiple handlers for each method (rest.get('*', fallback), rest.post('*', fallback), etc.).
Maybe there is already a better way of doing this?
Hey, @danielstreit! Thanks for reaching out with this suggestion.
While a generic fallback handler is an interesting topic, it seems that what you describe can be solved by #191?
Imagine having an API like this in your tests:
const server = setupServer(/* your handlers */)
// The API is to be discussed
beforeAll(() => server.listen({ onUnhandledRequests: 'error' })
We are planning to ship this feature in the next release of the library. Would this work for you?
Yes, that would handle the use case very well.
Glad to hear that!
I'm closing this issue in favor of #191 then.
Regarding the generic fallback handler, I can still recommend a solution using the current API. Consider this:
// This is your custom request handler function!
// That's an advanced technique, and it didn't make it to the docs just yet.
const withFallback = (resolver) => {
return {
predicate() {
// Match all requests, regardless of URL, method, etc.
return true
},
resolver,
}
}
setupWorker(
rest.get('/user', (req, res, ctx) => {...}),
withFallback((req, res, ctx) => {
// Handle any requests that didn't match the existing handlers.
// Throw exceptions, or return a mocked response.
})
)
Most helpful comment
Glad to hear that!
I'm closing this issue in favor of #191 then.
Regarding the generic fallback handler, I can still recommend a solution using the current API. Consider this: