Chapter 06: Data Mocking Library - MSW (Mock Service Worker)



When to mock API?
Let's look at the most common reasons to mock an API.
Development
Software is often being developed in an agile, competitive environment: shifting deadlines, parallel implementations, continuous delivery. Sometimes waiting on the API to be done is simply not an option. Most likely you are using some sort of mocking already: static fixtures, hard-coded state, or a third-party library.
When introduced in a dedicated layer, mocking can become a seamless pleasant experience, with one hardly noticing a difference when the mocking is gone.
Debugging
Most of the client-side issues are related to data. Invalid API call, missing error handling, or receiving an unexpected response—such scenarios happen daily during both development and production.
API mocking allows developers to model an exact API interaction that causes an issue. It's efficient in both debugging and fixing the problem, as one can mock a successful scenario easily as well.
Experimenting
Let's be honest: choices we make during development are not always the best ones. Technical debt and past architectural decisions may keep us from evolving our products, or trying brand-new technologies.
Mocks can help to see how the application would behave had it been written differently, without having to actually rewrite it, or committing to another ecosystem.


