Configuring Mock Service Worker
When testing React applications, one question often asked is how to test API calls. This question often leads to a follow-up question: “How can I make sure my network requests return the data I expect so that my tests always receive the same data and don’t become flaky?” There are many ways to answer these questions, and many implementations we can follow. The most common implementation often leveraged is mocking your data-fetching clients.
While this approach works, one thing that I’ve seen often in all the projects that I have worked on that followed this method is that the more tests you write, the more unmaintainable they become. This is due to the fact that mocking things such as fetch
or axios
comes with a lot of boilerplate code to take care of things such as different routes being hit, different responses for the same route, and cleaning up your client mocks to avoid tests leaking on each other. Let us not forget...