Tech we love: MSW mock library

Tech we love: MSW mock library

We use a range of tools to help us in our work for clients, and here we share one of our favourites: an API mocking library called Mock Service Worker (MSW). It is often helpful to use mock data while developing and testing, and there are plenty of options out there, but MSW's approach to delivering that data is just really clever and elegant. Let's talk about what makes it special and some cases where it has helped us.

For a long time we relied on replacing data-fetching methods in apps with temporary alternative versions which returned mock data. This was not ideal because our app using mocks was not the same as our app running against live services. We then turned to standing up servers which delivered mocks, but this brought its own problems, not least having to keep that server running locally during development and testing.

MSW changed all that. The core concept is the use of a service worker in the browser to selectively intercept HTTP requests and fulfill them with mock data where appropriate. This is clever for lots of reasons: because the application itself is unaware of it being mock data, because you can keep your mocks local, because you can even selectively enhance real remote responses, and because MSW is agnostic of frameworks and libraries, meaning you can use it to test just about anything.

Though its main attraction is the way it interacts with the browser, MSW has other tricks up its sleeve that make it a delight to work with. You can, for instance, also use it in a node.js environment, where it operates via request interception. This is commonly used to support unit tests in jest, but we have also found it useful to mock deeper back-end services while developing a GraphQL API.

Using MSW has been a game changer for us. Whether we are developing a UI against APIs which are inaccessible or unfinished, experimenting with enhancements to live APIs, or supporting functional tests driven by cypress.io or puppeteer - MSW has allowed us to test more efficiently and build better.

It is important to keep in mind that MSW helps developers deliver mocks, but they still have to build them. MSW works with just about any mock, which gives developers freedom to choose how to approach this. At Lola Tech, we usually start with simple data structures declared inline, or held on disk in JSON format. When we need to dynamically generate more realistic mocks we turn to tools like faker or kimera. In either case, MSW has worked with the mocks we have thrown at it.

The concept is elegant, the library is well maintained, the community is fun and supportive, the docs are excellent and the benefits are substantial - we love Mock Service Worker. Thanks @kettanaito and everyone who has helped build it into what it is today.

Contact us

Also see

Have a project in mind?
Let’s have a talk.

Contact us