So, we always tend to choose either mock client or server. But there's actually a thing in between, so we could choose neither. And that thing is called service worker. Service worker is an API that is a kind of a web worker, a JavaScript module that lives next to your application in a browser and executes in a separate thread.
This is an example of a worker file. So, workers have certain life cycle events and one of them is a fetch event. Worker triggers this whenever your app makes any kind of request. And in this handler, I'm writing that I want to look up the cache response and if there is a cache response, just respond with it, so don't do actual requests. But if there's no cache, execute the fetch as usual.
Now, you can see how with this, there's a huge potential to implement caching like this on the client side, but this got me thinking, what if instead of cached responses, we could return mock responses? Let's try that out. So the same worker, but this time in the fetch event, we're responding with this hardcoded response body and status code 200. And now, whichever request our app makes, it's going to leave the app and it's going to hit the worker and in response, this static response will be returned.
This is pretty great, so let's just use Service Workers for mocking and the problem is solved. But if you try to do that, you will be faced with a number of challenges. First of all, Service Workers have limited execution context and this is mainly due to security considerations. You cannot access the window object or DOM and obviously your client side code and your functions, utilities and libraries. Worker can get out of date and each time you register a worker, this does not necessarily push the latest worker to the browser and you may end up with an absolute worker, which is not nice. When you hard load the page, the worker will stop and you would have to reload the page to see it running again. This creates a distorted developer experience. Workers also control unrelated clients and they do it because the worker establishes connection with the client based on its URL. So you may open a completely different project on the same URL, on localhost, and see an unrelated worker kicking in and trying to mock responses. And this is just confusing.
Despite those challenges, I like the idea. And a couple of years back, I wrote the library that's called MockServiceWorker or MSW for short. And it leverages the ability of ServiceWorker to intercept requests and does that gracefully. MSW is the closest thing to an actual server without having to create one. And this is thankfully to ServiceWorkers. Let me show you how the workflow with the library looks like before we dive into internals. So first things first, I'm going to tell the library which requests to capture. And I'm writing these things called request handlers, just functions that described request information and which response to produce.
Comments