Subject Under Test
A generic fetch item list hook used to fetch data from the API server, designed for a generic item list component tem...
For further actions, you may consider blocking this person and/or reporting abuse
Hey Rex, I really liked how you handle error responses by setting specific status code on localStorage. It would be nice if msw had a proper solution, but this approach is very interesting because avoid jests mocks or implementation on production code.
Hey, Guilherme.
There are multiple ways to mock error scenarios with MSW. As the default approach, we recommend explicitly specifying which endpoint must return an error:
I understand it may feel verbose but having an evident handler-response override declaration is vastly beneficial in the long run. Generally, prefer explicit behaviors, it's better for debugging and allows you to grasp all the changes the test establishes in a direct way.
In the latest version you can use
rest.all()
if you wish to make all requests to result in the 500 status code:I wouldn't recommend this particular approach with
localStorage
because it gives you little idea of what the following line affects, unless you inspect your testing setup:If you feel like the observability is a little price to pay, you may use this (in the end, it's your setup!). Also, consider relying in a global variable directly, there's no actual reason to bring in
localStorage
:Please let me know if there's a certain difficulty you experience when mocking error responses. It's always a good idea to provide your feedback via GitHub Discussions. Thank you!
Bringing the expert into the discussion makes a huge difference!
If testing query directly, a separate bad path approach is the best because the test can easily change the url.
But when it’s indirect, say if we are testing a form component which would make a request, we would have to touch the implementation details to manually change the url, which is less ideal.
Assuming we keep the mocked api very simple, a switch for a bad path for all apis may work better. If it is simply and works the same for all endpoints, it could be a known convention for the team. This also resembles the real api closer: the same api point can return good or bad response.
I love the idea of using global instead of local storage. I will make the switch, thank you!
Well, you're still relying on that implementation detail in your handlers. I do share the notion not to expose too many internals in tests—on that I wholeheartedly agree. Yet observability is also a thing to consider, especially when it comes to the testing setup. I'd still go with explicit handler/override declaration 99% of the time.
Yeah, that is a perfectly valid way to model your request handlers. You can either focus each handler on a particular behavior and utilize overrides via
server.use()
, or scope handlers per resource, like in a conventional server, and include any conditional behavior within. I'd say it's a personal choice, which comes from the complexity of the mocked API before anything else.My main concern with using global error mocking is the same as using anything globally: it may be hard to keep track of global setups. This is partially solved by descriptive naming (as in
global.shouldRequestsError
) but it still introduces an implicit piece of logic that is detached from MSW.The "ideal" setup, in my opinion, would be to expose internals by reference. That's a cost-free way of exposing internal details.
Thank you! I didn’t know the override, my bad, I should read the docs a lot more.
With the override, I am very happy to ditch the global error mocking. So much clearer and so elegant!
@kettanaito Thanks to your help, I have updated @mockapi/msw removing the global error handlers. I also recommended the use of
server.use
to override endpoints in thereadme
. Phew, almost mislead the community.@kettanaito I also updated the tests and setup here in this post to reflect the best practices.
Hey @kettanaito
I love the
server.use
override in tests, very handy! However, how do you handle this in the browser? In that case you probably would have to use a global override as suggested above.Hey.
The browser has its worker.use() counterpart that behaves identically to
server.use()
. You can still leverage "happy path" scenarios provided to thesetupWorker()
call, and then append runtime behavior viaworker.use()
.Yes, to be able to access the worker in the first place you'd have to expose it as a global variable.
Thanks for the quick reply!
This might be a dumb question but can this then be used in chrome console window?
I just tried but still not seeing the error response, I assume my "happy path" worker which is running when my app loads in dev is overriding it. I basically just want an easy way to simulate error scenario while developing locally.
Executing that in the browser console should apply the override. If it's not applied, double-check the correctness of the request path. When mocking on runtime, I find it much more comfortable to bind the handlers overrides to the URL query parameter.
Since the handlers are loaded on runtime, refreshing that runtime will offload them forever. That's where URL-as-state is a more developer-friendly pattern but it takes some time to set up.
Gotcha. The app I am currently looking at does not have react-router or anything similar implemented, so doesn't update the route or query string in the address bar url as the user clicks around. The app is also hosted on a different domain to the api. Therefore, what do you think about just reading the query string via the window location within the handler itself? Like this:
I'd probably use the same approach to simulate an empty state in the UI:
Thank you Guilherme.
It feels like a hack but I think it is not.
It is a very interesting topic to discuss, what msw could have done as a proper solution? If you ask me, I would say it is out of scope for msw. msw provide the infrastructure much like any other API server, it is up to us to return whatever is required.
I think we should not develop the mocked API as if we are developing the real thing, there shouldn't be any complicated logic inside a mocked API. We must take the shortest and simplest route to mimic the responses we expect from a real server. We shouldn't care about how and why the response is returned from the real API.
The tests need to communicate with the mocked API and I think using things like
localstorage
works is one of the "proper" ways. I could be wrong, @kettanaito what do you think?Hey, Rex.
I wouldn't recommend using
localStorage
for global error handling but, in the end, it's your testing setup and you should evaluate what works best for you, taking benefits/trade-offs into consideration.I've written a more detailed response to Guilherme above, let me know what you think about it.
Thank you once more for this fantastic article!