Set base URL for matching relative paths in request
See original GitHub issueIs your feature request related to a problem? Please describe.
I have different API URLs for different environments, for instance in development it’s http://localhost:8080
where in production it’s a relative path /api
. The paths are also different for Storybook, and I am using MSW in those as well.
So right now I have to create the full request URL (absolute or relative) for all the MSW handlers, e.g.
function apiURL(path) { return process.env.REACT_APP_API_URL + path; }
setupWorker(
rest.get(apiURL('/users'), (req, res, ctx) => {...} )
);
Describe the solution you’d like
I’d like to be able to set a base URL for MSW, so that all relative paths are treated as extending from that, similar to the baseURL
config property in Axios.
Describe alternatives you’ve considered The above approach works, but it’s annoying to have to wrap every path with a function like that.
I also tried using wildcards like */users
, which works, but there is always the possibility that it would end up matching a different request, either from my application directly or from some other resource being pulled in from a library.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:6
- Comments:9 (7 by maintainers)
Top GitHub Comments
Unfortunately, I have to close this. See the reasoning behind why this feature costs more than it brings.
It’s officially recommended to create a custom high-order function if you wish to reuse the same base path for multiple handlers. Like so:
Hi @marcosvega91, @kettanaito. I initially imagined it as a part of the options to setupWorker or setupServer, similar to Axios (https://github.com/axios/axios#creating-an-instance)
That would probably be the simplest way, but the graphql implementation you linked above would offer more flexibility for mocking different APIs simultaneously.
In order to keep the API consistent across both
rest
andgraphql
maybe something that would be consumed like: