all Technical posts

How to Mock API Requests in Front-End Development?

Get similar application behavior with or without mocks

Let's skip the waiting room!

Nobody likes to wait. As with doctors’ appointments, in development (or in any other context), things can get out of hand and take a lot longer than originally estimated. This is due to numerous reasons.

As a front-end developer, this can mean that there are some situations where there is just no API available. Yet you’re booked for a task that consumes that API, and the deadline is closing in. So how do you proceed? 🤷‍♀️

The first attempt

You may have already tried to fix this yourself. You may have created your own server (with for example ExpressJS), run it, faked the API and returned mocks. This will have done the trick, for sure. But it all seems a little cumbersome, right? You would have had to manage and run 2 “projects”, and already had prior knowledge of how ExpressJS works.

Or perhaps you bypassed the API call, wrote some custom time-out function to make it appear “real” and returned a hardcoded state?

I’m guessing that worked, but it’s not pretty. For starters, when doing this you would have needed to re-code it when the API is finished, and nobody likes to do double work.

So luckily, there is another way! 🍀

Mock Service Worker (MSW)

MSW is an API mocking library that uses the Service Worker API to intercept the actual requests.

The Service Worker API is designed to intercept requests on a network level. MSW leverages this, making the mocking more coherent. This results in similar application behavior, with or without mock. This is not only behavior, but it also does not require any changes to the actual application’s code. Therefore, you only need to code once! 🤘

What about DevTools, you say? No need to worry there: open the “Network” tab and observe your requests like you would normally do. 🤩

You can use MSW for the (waiting) scenario we described above, but it also comes in handy for debugging (like error handling) and experimenting purposes.

How does it work?

MSW registers a Service Worker that will listen to the application’s outgoing requests via the fetch event, then direct those requests to the MSW library. It can then send out your custom mocked responses to the Service Worker, which will respond.

Let’s look at a high-level diagram of MSW’s request flow:

You’ll need to write declarative request handlers to capture your requests, as well as providing a response resolver function that returns a mocked response.

These handlers co-locate with the rest of your app, so there is no need to add extra “projects”.

Fake it 'til you make it!

So let’s fake some requests by adding some request handlers!

If we break it down, a basic mock definition file looks a bit like this:

Ideally, you’ll separate your handlers, configuration, and registration into different files, but for brevity purposes, we didn’t. See the installation guide for more information.

Let’s zoom in a bit on the request handlers.

Every request handler needs a method, a path, and a response resolver function that returns the mocked response.

If we put this all together, we’ll get something like this:

Whenever you make a request to /product/:id it’ll return your awesome product.

A powerful feature is to conditionally mock requests. Suppose you want to load the actual server response for a specific user, or you want to test both a successful and error response by just using a different id.

With that you can easily test out different (edge-) cases in your application flow, resulting in a more robust application.

There are a lot of other cool features available such as “custom response composition” and “custom response transformers”. But we’re not going to go into that today.

Verifying it all works

Once you’re done creating your request handlers and you’ve started up your application, just open up your browser DevTools’ console and look for the following message:

[MSW] Mocking enabled

And with that, any requests that match your custom handlers will now be intercepted and mocked. Be sure to check out the logs for intercepted requests, as they can be handy for debugging purposes from time to time.

Happy mocking! 🎉 🎉 🎉

Subscribe to our RSS feed

Thanks, we've sent the link to your inbox

Invalid email address


Your download should start shortly!

Stay in Touch - Subscribe to Our Newsletter

Keep up to date with industry trends, events and the latest customer stories

Invalid email address


Great you’re on the list!