Mocking WebSocket APIs with Mock Service Worker
course
Browse
Find courses, lessons, articles, talks, and podcasts.
50 resources
Showing 1–24 · Page 1 of 3
course
article
<ResourceWidget resource="youre-currently-reading-a-series" /> API mocking is a technique to intercept HTTP requests and respond to them with mocked responses. We often use API mocking during development and testing to gain control of the network, modeling it to suit our needs. And, as with many things, we rely on third-party libraries to implement request interception reliably and provide us with API mocking capabilities. **But have you ever wondered how those libraries work?** In this mini-series, you and I will be taking a deep dive into how different API mocking solutions work to see what benefits and downsides they have, as well as just broadening our understanding of HTTP requests in JavaScript. --- ## The Steps of API Mocking In a nutshell, API mocking consists of two sequential steps: 1. Intercepting an outgoing HTTP request; 2. Responding to that intercepted request with a mocked response. There are quite a number of ways to implement either of those steps in an API mocking solution. To build a truly great one, we need to ensure a proper balance between the code’s integrity and the amount of control this solution gives us. But, most importantly, we need to understand how requests are represented in JavaScript and know about the different stages that a request goes through before being performed. And like with many things in life, we will learn about all that on a journey. ## The Request Journey Every story has its beginning, and ours begins from a request. You see, request interception is rather tightly coupled with how that request is being made. If we wish to understand the difference and tradeoffs of various API mocking approaches, we should first understand how HTTP requests can be made in JavaScript. So, make sure your headers are fastened and cookies jarred, we are going on a request journey! ## The Request Client Any request starts with the intention to read or change data. We put that intention into code and provide it to a *request client* to carry it out*.* A request client is, essentially, any API (native or third-party) that concerns itself with accepting a request declaration and executing it. For example, one of the most common browser APIs to perform requests is Fetch API: ```js // We have an intention of fetching all movies. // To describe that intention, we perform a "GET" request // to the "/movies" endpoint on the server. fetch('/movies') ``` In practice, you may be using all sorts of different clients, like Axios or "got", and your choice will often depend on the kind of request you wish to describe (e.g. you may want to use a specialized GraphQL client, like Apollo, to describe GraphQL requests). Once the request client accepts our intention (request description), it returns us the means to monitor that request execution and, eventually, handle the received response from the server. In the example above, the `fetch` call would return a Promise resolving to a `Response` instance that we can read: ```js // The fetch Promise resolves to a "Response" instance // that allows us to handle the response (e.g. get its // status, headers, or read its body). const response = await fetch('/movies') console.log(response.ok, response.status) ``` For us, developers, the request client is often where our interaction with the request ends, but for the request itself, this is only the beginning. While request clients provide us with a great way to perform and manage requests easier, they are just abstractions for the underlying code doing all the heavy lifting. And that is precisely where our request is headed. ## The Environment No matter the request client, our request will inevitably reach the standard API of the environment responsible for handling HTTP requests. While we may interact with that standard API directly, when using third-party request clients we delegate that interaction to the client, and so the construction and handling of a request becomes an implementation detail of the request client. For example, when using Axios, it will represent our requests as `XMLHttpRequest` in the browser and `http.ClientRequest` in Node.js without us even knowing. But we are here today to go beyond third-party abstractions and learn about those environmental APIs, aren’t we? It’s important to keep in mind that each environment implements its network module differently. As JavaScript engineers, we are mostly interested in the browser and Node.js environments. Let’s take a look at what native APIs exist there to represent a request. ### **Browser** **window.fetch** Fetch API is one of the most common ways to make requests on the web. Introduced to the world in 2015, it launched as a step forward from `XMLHttpRequest` and, without a doubt, has changed our developer lives for the better. ```js fetch('https://api.example.com/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Alice' }) }) ``` The browser implementation for fetch is in the native C code and the `window.fetch()` call is the last surface that we can interact with. <LessonWidget course="sell-products-using-stripe-checkout-and-netlify-functions" lesson="javascript-use-the-native-fetch-api-to-load-json-data-into-an-html-page" /> **window.XMLHttpRequest** XMLHttpRequest made its first public appearance as a fully-functional API to dispatch requests in 2002. This may be surprising for some, but XHR is still shipped in the browsers to this day and is a legitimate way to make requests. Moreover, XHR exposes a few capabilities that even modern Fetch does not have, such as monitoring a request’s progress and request cancellation, which was not possible via Fetch prior to `AbortController` becoming a thing. ```js const request = new XMLHttpRequest() request.open('POST', 'https://api.example.com/users') request.setRequestHeader('Content-Type', 'application/json') request.write(JSON.stringify({ name: 'Alice' }) request.send() ``` Similar to `window.fetch`, XMLHttpRequest’s roots go deep into the native browser code without any intermediate layer to attach our mocking logic. ### **Node.js** **http.request** (https.request) Node.js provides us with a high-level API to perform requests via `http` and `https` modules. While they share similar methods, like `.get()` and `.request()`, their implementation differs as they handle different request protocols. ```js import https from 'https' const request = https.request('https://api.example.com/users', { method: 'POST', headers: { 'Content-Type': 'application/json' } }) request.write(JSON.stringify({ name: 'Alice' })) request.end() ``` The `http.request()` API is what most of the request clients in Node.js use internally. Perhaps it’s the verbosity of said API that gave birth to so many request clients in that environment, to begin with (my wild assumption here). **http.ClientRequest** Moving further down the call stack, the `http.request` represents (and handles) requests using the `http.ClientRequest` class. It’s fair to mention that some libraries and polyfills utilize this class directly, circumventing the higher-level API altogether. That being said, constructing a request via `http.ClientRequest` is similar to using `http.request`, and the difference may not even be visible to a naked eye at times: ```jsx import http from 'http' import https from 'https' const req = new http.ClientRequest({ protocol: 'https:', host: 'api.example.com', pathname: '/users', headers: { 'Content-Type': 'application/json', }, agent: new https.Agent(), }) req.write(JSON.stringify({ name: 'Alice' })) req.end() ``` > Note that it’s the same `http.ClientRequest` class that describes both HTTP and HTTPS requests, unlike the `http.request` and `https.request` distinction at the higher level. > **net.Socket** Let’s go even *deeper*. Any HTTP request is, essentially, data transferred over a socket, and Node.js has a `net.Socket` class to describe just that. ```jsx import { Socket } from 'net' const socket = new Socket() socket.connect(443, 'api.example.com', () => { socket.write('POST /users HTTP/1.0\n') socket.write('Content-Type: application/json\n') socket.end(JSON.stringify({ name: 'Alice' })) }) ``` The fact that we are sending raw HTTP messages over the wire should give you a good impression of how low-level the Socket API is. Although you are unlikely to use this API directly, it’s still an inevitable part of the request journey in Node.js, and, as a consequence, important to our choice of the API mocking approach. **Honorable mentions** Node.js 17 adds a global `fetch` API similar to that in the browser. Since they comply with the same specification, the `fetch` in Node.js represents requests and responses using the `Request` and `Response` classes respectively, but those still act as abstractions over the low-level APIs we’ve touched on above. Once the network module does its job, the request finally gets performed, leaving the environment and traveling down the fiber to the requested server. ## The Server The server is where requests come to ~~die~~ resolve. The server is the farthest context from our request intention, as it’s a different environment often implemented in a different language than our application, having intricacies of its own. However, once the server resolves the request, it sends the response through the same journey so it would, eventually, return to the request client. **Thus, once our request reaches the server, there’s little we can do to affect it from the client-side runtime.** --- ## Conclusion The purpose of any journey is to improve and change those courageous enough to embark on it. And the request journey we’ve just gone through is no exception. As we’ve learned about the various ways to describe requests and what checkpoints each request undergoes, we can proceed to draft the possible ways to implement API mocking in our application. That’s precisely what I will be covering in the next post. <ResourceWidget resource="understanding-api-mocking-next-part"/>
article
> A humble reminder that in this series we’re learning the nitty-gritty of how API mocking _libraries_ work. Although you’re unlikely to use this knowledge directly (well, unless you decide to write such a library!), it’s still crucial to understand how these libraries work so you could reason about their advantages and disadvantages whenever you come to use one. <ResourceWidget resource="understanding-api-mocking" /> Now that we know every step that a request goes through, let’s take a deep dive into different ways of implementing API mocking. The interception of requests is at the core of any API mocking solution. Despite there being dozens of libraries to choose from, they all implement one of a few possible algorithms to enable request interception, and those algorithms are directly connected to the request journey. Today, we are going to take a detailed look at those interception algorithms for both browser and Node.js, learn how they work from the inside, and compare their pros and cons to see how they differ and what price you pay when adopting one. --- ## Purpose of interception The purpose of intercepting requests is to allow our API mocking solution to perform the following: - Know when an outgoing HTTP request occurs in your application; - Have enough information about the request to perform request matching (to find out which mocked response belongs to which request); - Respond to the intercepted request in the way that the request client originally expects. The challenge of request interception comes from the fact that there isn’t a standardized API in JavaScript to achieve it. Thus, historically, developers have been coming up with various ideas on stubbing, patching, or otherwise excruciating native modules to provide the so sought interception. Before we dive into various interception algorithms, let’s quickly revisit what happens to a regular (non-mocked) HTTP request when it’s performed in your application:  In practice, intercepting an outgoing request comes down to hijacking its journey at a certain point. Based on that point, all interception algorithms can be divided into three main categories: 1. **Request client-based;** 2. **Environment-based;** 3. **Server-based.** The point at which we decide to interfere with the request journey matters because it provides its own advantages and disadvantages. Let’s take a closer look at those three approaches to request interception. <EmailSubscribeWidget /> --- ## Request client-based interception The most straightforward way to know when a request happens is to detect it on the request client level (i.e. when the request is constructed). This is a common approach for API mocking in the wild, and, given the limitations of the environment, the only approach one may take in the browser (we will learn at the end of this article if that’s truly the case!).  I will be using `window.fetch` in the browser to illustrate how this algorithm works. Naturally, it’s not limited to the browser, and its principle applies to Node.js as well as any other request client (`XMLHttpRequest,` third-party libraries, and so forth). In practice, intercepting requests on the request client level means _stubbing_ that client: ```jsx // browser.example.js window.fetch = async (input, init) => { const request = new Request(input, init) console.log("request happened!", request.method, request.url) } fetch("/movies") // "request happened! GET /movies" ``` > A _stub_ is a fake structure with a pre-determined behavior, such as request interception and matching in our custom `window.fetch` function. A _mock_ is a fake value, such as the mocked responses we will be constructing later on. We’re replacing the native `window.fetch` with our own function, which lets us know whenever a call to `window.fetch` happens. Since we now, basically, control the fetch, we can do whatever we want with each request. And what we want in the context of API mocking is to resolve certain requests with mocked responses. I will extend the example above to include a basic request matching so that it would respond to a `GET /movies` request with a fake list of movies. ```jsx // Store the native, un-stubbed reference to "window.fetch". const nativeFetch = window.fetch // 1. Request interception. // React to any outgoing requests. window.fetch = async (input, init) => { const request = new Request(input, init) // 2. Request matching. // Check if we should respond to the intercepted request using mocks. if (request.method === "GET" && request.url.endsWith("/movies")) { // 3a. Mocked response. // Manually construct a Fetch API Response instance and resolve // the request promise with it. return Response.json([ { title: "The Godfather" }, { title: "The Lord of The Rings" }, { title: "The Dark Knight" }, ]) } // 3b. Passthrough responses. // If the intercepted request doesn't match our predicate, // perform it as-is using the previously stored native fetch. return nativeFetch(input, init) } ``` Whenever our application performs the `GET /movies` request using `fetch()`, it will receive a mocked response instance instead of actually performing that request: ```jsx // Keep in mind, "fetch" is stubbed here by our own implementation. const movies = await fetch("/movies").then((res) => res.json()) console.log(movies) // [{"title": "The Godfather"}, ...] ``` This is a very primitive illustration of the request client-based API mocking. We can improve quite a few things about it, like moving the hard-coded request predicate outside, wrapping the whole logic in a consumable API, and generally making it more versatile to suit different use cases. But I would like to focus now on the benefits and drawbacks of this particular approach. <Callout> Check out <a href="https://egghead.io/courses/debug-http-with-chrome-devtools-network-panel" target="_blank" rel="noopener">Debug HTTP with Chrome DevTools Network Panel</a> by Mykola Bilokonsky to become more familiar with HTTP requests in the browser and better understand the ways in which our applications exist in a connected context. </Callout> <CourseWidget course="debug-http-with-chrome-devtools-network-panel" /> ### Benefits of the request client-based request interception **Benefit #1: Simplicity** The client-based interception is the most straightforward approach since the request client itself has the highest level of context on the HTTP request journey. All we need to know to make it work is the input and the output of the request client (i.e. its call signature). As long as our algorithm complies with that signature, we get a functioning API mocking. Taking `window.fetch` as an example, as long as we supply a correct input (`input` and `init` arguments of the `fetch` function) and return the correct output (the `Promise<Response>`), our algorithm is guaranteed to be compatible with the standard fetch implementation. This puts minimal overhead on this algorithm in the context of accounting for internals, such as request client implementation details or specifics of the environment where it’s being used. **Benefit #2: Performance** The client-based interception is also rather performant since we introduce the stubbing logic at the very first step in the request journey. In other words, only the actual public API of the request client gets called—everything after that is our own mock implementation. This may be beneficial in mock-heavy applications but do bear in mind that it comes at a high price (later on that in the drawbacks). **Benefit #3: Context** Basically, you must’ve noticed already that all the benefits of this interception approach come from it being way up in the request chain. Naturally, this also means that we have the most context exposed to the implementation of this algorithm. And the more information about the outgoing request our algorithm has, the more feature-rich and versatile it can get. This will become more evident once we dive into environment-based interception where the request client context is often coerced or lost altogether. ### Drawbacks of the request client-based request interception **Drawback #1: It’s request client-specific** The client-based interception is, by definition, bound to the particular request client. In the example above, we’ve implemented the interception for requests made via `window.fetch`, but that will not affect the requests made with `XMLHttpRequest`. Now, think about these two as any two other request clients you may be using: fetch and Axios, Apollo and XMLHttpRequest, etc. Different request clients co-existing in a real-world application is not an unusual thing. But as each client is different, we’d have to implement interception for each and every one of them, respecting the specifics of how they declare and handle requests and responses. Needless to say that such implementation is highly brittle and doesn’t scale by design. However, common ground can often be found. For example, we may concern ourselves only with `fetch`and `XMLHttpRequest` to cover any other request client that runs in the browser, as all of them will rely on those primitives. While this is true, `fetch` and `XMLHttpRequest` are still dramatically different, so we will write two different implementations to achieve the same thing—to mock an API. All we’re doing by stubbing a request client is replacing it with a seemingly compatible “fake” implementation. While we may achieve API mocking as a by-product of that, it doesn’t free this approach from a number of other disadvantages. **Drawback #2: We throw away the request client** Since we no longer call the native `window.fetch` on mocked requests (that’s the entire point, right?), we effectively disregard whichever logic fetch has around making requests. One prominent example of such logic is the _request input validation_. In HTTP, you cannot make a GET/HEAD request with a body—that’s simply against the specification. If you try to do so using a plain version of `window.fetch`, you will get a runtime exception: ```jsx fetch("/movies", { body: "hello" }) // TypeError: Failed to execute 'fetch' on 'Window': // Request with GET/HEAD method cannot have body. ``` Native fetch guards us against making a mistake in our code, which is great. But will that be the case if we use our patched version fetch? ```jsx window.fetch = async (input, init) => { /* mocking logic */ } // Performing a GET request with a body is a violation // but since we're disregarding the native code that does // this validation, we're allowing invalid behaviors. const response = await fetch("/movies", { body: "hello" }) console.log(response.ok) // true ``` Ouch! We’ve just performed a request that doesn’t make sense but our application was okay with it. Maybe it even got a mocked response back, continuing to work as if everything was normal. But it wasn’t normal. That `fetch` call is a problem and it _will_ throw in production, crashing the app for our users. That’s not even the worst part. Since we often use API mocking in testing, any test concerning this faulty code will pass because it runs in a fantasy land where requests are not validated before being declared. The fantasy we’ve created ourselves by replacing `window.fetch`. A natural thing to say here is that we can add that input validation to our custom fetch and be done with it. Keep in mind that missing request body validation is only a single example of how dangerous it may be to replace native code. Unless you wish to implement the entire Fetch API specification (which library authors certainly don’t want to do), you will always compromise on the application’s integrity whenever a native module like `fetch` is stubbed. **Drawback #3: Requests never truly happen** Somewhat derivative from the previous point, the lack of the “clean” request client call also means that whichever request intention we’ve expressed with it will never actually happen. You can observe it yourself by looking at the “Network” tab of your browser’s DevTools whenever a mocked request occurs—_it will not be there_. But do not get confused, the Network is not lying to us here: the request never really happens, we only _pretend_ that it does. So, the request never happens, why is that a big deal? Although we are mocking things, it doesn’t justify throwing away the parts of our application, and HTTP requests are a rather crucial part at that, don’t you agree? By replacing the request client, our application suffers from the following issues: 1. **It hurts observability**. We can no longer observe the outgoing traffic, be it the browser’s DevTools or any kind of request monitoring tools in Node.js. This may lead to confusion while developing and testing, if not bugs related to other parts of the system reacting to outgoing requests. 2. **It alters the system**. By stubbing the request client, we change our application. What does `window.fetch()` do in production? It taps into the browser’s native code. What does it do during automated tests? It hits our mock function, ignoring any underlying browser API whatsoever. That is a deviation, and the more we let our system deviate, the more we’re working with a different system. I illustrate the practical manifestation of this in the previous drawback by showing you how we can perform a completely invalid request in tests and it’d still qualify as passing because our mock doesn’t know better. > I understand that the words “mocking” and “alteration” have become practical synonyms over the years but I’m writing this piece to stir a discussion that they don’t have to be. We can achieve API mocking without sacrificing our application’s integrity (in fact, leaving it entirely intact!) and I will prove this to you over the course of this series. --- ## Environment-based request interception Since we are talking about request interception in JavaScript, by “environment” I will refer to Node.js as the environment. Although the browser is another major surface where JavaScript can run, its environment is rooted deeply into the browser’s internal and native C code, to which we have no access.  In Node.js, however, the entire runtime is our playground. At least enough so to intercept requests on the level of underlying request-issuing modules, mainly `http` and `https`. As we’ve learned in the previous article, any request in Node.js bubbles down to either high-level (`http.ClientRequest`) or low-level internals such as `net.Socket`. Naturally, those internal modules become the primary area of implementing API mocking for us. The most common approach to request interception in Node.js is stubbing the `http` module or, to be more precise, its `ClientRequest` class. In practice, this approach is not much different from the one described in the client-based interception above. Here’s an example of how to intercept HTTP requests in Node.js: ```jsx const http = require("http") // Replace the "ClientRequest" class with our own implementation. // This way we can react to newly constructed requests. http.ClientRequest = function ClientRequestOverride(args) { // Node's call signatures are rather flexible // so we need to nail it down to a predictable shape. // There are fewer stars in the sky than there are ways // to construct "http.ClientRequest" in Node.js. const [method, url, options] = normalizeArgs(args) if (method === "GET" && url.endsWith("/movies")) { // Define the mocked response. const response = new http.IncomingMessage(this.socket) response.statusCode = 200 response.statusMessage = "OK" // Write response headers. response.headers["Content-Type"] = "application/json" // Write response body. response.push( new TextEncoder().encode( JSON.stringify([ { title: "The Godfather" }, { title: "The Lord of The Rings" }, { title: "The Dark Knight" }, ]) ) ) // Mark the response as complete. this.response.push(null) this.response.complete = true this.writableEnded = true this.res = response this.emit("finish") this.emit("response", response) } } ``` > There’s quite a number of things omitted from this example for simplicity’s sake. Even at this scope, it should give you a good overlook that the lower you get in the call stack, the more verbose your implementations become. The only remaining thing is to import this module anywhere in a Node.js process and it would do its magic, replacing the `http.ClientRequest` class _globally for that entire process_. Any subsequent constructs of that class will yield the `ClientRequestOverride` instance we’re written above. While the majority of request libraries rely on the `http` and `http.Client`, I must stress that there are some that omit that construct entirely, utilizing low-level socket communication to implement the request logic (one of such examples is Undici, which lay in the foundation of the global `fetch` in Node.js). Obviously, the patched module above will have no effect on such libraries, so we need to account for that in real-world scenarios. ### Benefits of the environment-based interception **Benefit #1: More of the request client’s logic gets executed.** Because this algorithm doesn’t meddle with the request client itself and instead replaces the universe in which the client is being run, it allows the client to execute in its entirety. Any built-in logic that the client has, like input validation or response normalization, will be performed just as it would in production, which is great. **Benefit #2: Request-client agnostic**. Applying the interception on the environmental level means that _any client_ will eventually arrive there. This makes environment-based API mocking client-agnostic and, as the result, more versatile when it comes to supporting any request client your application may use. **Benefit #3: More control.** Compared to stubbing the request client, environment-based interception provides the API mocking solution with more control since it’s dealing with a lower-level request code. For example, stubbing the `http` module allows our solution to tap into the socket connection because it’s available on the `ClientRequest` level. ### Drawbacks of the environment-based interception **Drawback #1: Throwing away the environment** Similar to the stubbing of `window.fetch()`, doing so with the native Node.js modules means we’re throwing away whichever internal behaviors they have and replacing them with our own implementation. Not only have we now become obliged to adhere to the native behavior of those modules to reduce bugs, but we also need to re-implement some of the vital features, like request validation, because it’s performed when establishing a Socket connection, which won’t happen anymore. Overall, the environment-based interception is still subjected to the same drawbacks as the client-based one, meaning that the HTTP requests won’t actually happen and that it’s entirely possible to construct a request instance that doesn’t make sense otherwise. **Drawback #2:** **Getting rather low-level** Despite the `ClientRequest` class being a high-level API in Node.js, you can already notice how deeper we have to go into this module’s details to implement mocking. For instance, to correctly respond to an intercepted request we need to know that Node.js sets the internal `res` property of `ClientRequest` to the response instance (`IncomingMessage`) and expects an empty response body chunk (`null`) to be written to the response buffer to indicate a successful finish of the response. If we miss those internal details, our intercepted requests will hang indefinitely without any indication. This is one of the reasons why stubbing native modules can be dangerous, as the stubs become closely connected with the environment’s implementation of those modules, become aware of their internals, and may get fragile and flaky as the result. --- ## Server-based request interception Although we cannot affect the request once it hits the server, it doesn’t mean that the server level is not an option to implement API mocking. Surely, we don’t want to reach the actual server but what if our request reaches a _mocked server_ instead?  In practice, this means creating that mocked server and integrating it as a part of our testing/development workflow: ```jsx // mock.server.js import express from "express" const app = express() // This is a "GET /movies" route handler on our mock server. app.get("/movies", (req, res) => { res.json([ { title: "The Godfather" }, { title: "The Lord of The Rings" }, { title: "The Dark Knight" }, ]) }) app.listen(3004) ``` ```jsx // src/routes/movies.jsx export default function Movies() { // In our application, we need to parametrize the server URL // so we would request resources from our mock server during tests/development. const movies = useApiRequest(`${process.env.API_URL}/movies`) // ...render the list of movies in the UI. } ``` ```jsx { "name": "my-app", "scripts": { "start": "some-framework start", "start:mocks": "node ./mock.server.js", "test": "concurrently \"API_URL=http://localhost:3004 npm start\" \"npm run start:mocks\"" }, "devDependencies": { "concurrently": "latest" } } ``` All we have to do to make this work is to start the mock server locally and route our application’s requests to it instead of the production server. That sounds fairly straightforward. Now, let’s talk about what this approach implies. <Callout> To learn more about how to build an API with Express check out <a href="https://egghead.io/courses/building-an-api-with-express-f1ea" target="_blank" target="noopener">Building an API with Express</a> by Kevin Cunningham! </Callout> <CourseWidget course="building-an-api-with-express-f1ea"/> ### Benefits of the server-based interception **Benefit #1: Request client and the environment are intact** As the name suggests, the server-based interception focuses on the server, the preceding request client and environmental logic remain intact. We don’t introduce any stubs and we don’t meddle with the request client in any way, which is fantastic! As a result of this, the requests we make actually happen and are observable in the system. **Benefit #2: Standalone server** Since we’re establishing an actual living and breathing HTTP server, it’s also available in any other context should we need it. For example, we can curl it straight from the terminal or share it with our colleagues on the same network. Based on these benefits, server-based interception may look like a perfect approach. But before you jump to that conclusion, let’s take a look at its drawbacks because, unfortunately, they are rather significant. ### Drawbacks of the server-based interception **Drawback #1: Altering the system** Once again, we circle to the system alteration point. Unlike the previous two approaches where we throw away either the client or the environment, with the server-based interception we’re preserving them both. Well, almost. Since we don’t want to hit the actual production server, we need to _direct_ our requests to the mock server instead, which means changing our intention behind those requests. Let’s take another look at the `GET /movies` request from the previous example: ```jsx const movies = useApiRequest(`${process.env.API_URL}/movies`) ``` In order for our application to hit the mock server, we introduce the `API_URL` environment variable as a part of the resource URL so we wouldn’t request actual production resources. Here, there it is—we _don’t_ request actual production resources. Instead, we’re routing all requests to the mock server to handle. In other words, the value of the `API_URL` variable bring turn our entire application to an alternative universe, and it’d be a universe quite different from the one that runs in production. The easiest way to demonstrate why this is crucial is to imagine what value `API_URL` will have in production. It’s probably something like `https://api.myapp.com` or `https:/myapp.com/api`. Except, the second URL has a typo in its protocol, which makes it invalid. It’s a rather mechanical mistake, not a big deal, we write tests to help us avoid things like that. But will they help? Well, our requests hit `http://localhost:3000` (the mock server) during tests, and _that_ URL is indeed correct. What we are getting is perfectly passing tests and perfectly broken production. My point here is that you should be extremely cautious when introducing deviations to your system—things that make it behave differently from its “base” (production) state. > **The more you alter the system under test, the more you’re testing a different system.** **Drawback #2: Writing and maintaining an actual HTTP server** Do not be fooled, despite it being a “mock” server, it’s still an actual HTTP server you have to write and maintain. As with any code, writing the mock server subjects its logic to bugs and inconsistent behaviors, which may result in flaky and unreliable tests. Even if you decide to use third-party libraries to speed up and simplify this process, you will still be doing the same thing just over a third-party abstraction, such as a JSON manifest describing server-side routes. I like using one particular example to illustrate this. Imagine the request your application makes as a person and the actual server as a bank. Without any API mocking, the (test) person would walk into the bank and perform real operations, which is not desirable in tests. If we use request client-based interception, we’re giving them noodles for arms, altering the human body construction and behavior. The real, production person won’t have those alterations, and so we’re effectively conducting tests on a made-up, seemingly-compatible being, hoping that it passes for humans. Well, what does it make a mock server in this allegory? It’s an _entire fake bank_ we built for the person to walk in and interact with. We’re keeping the real person, no modifications, but everything else around them suddenly becomes fake. The integrity of such a testing setup and the confidence provided by such tests is directly related to the faithfulness of the “fake bank” implementation, which is never entirely complete by design. **Drawback #3: Increased complexity of development pipelines** Any process that depends on API mocking now, be it automated tests or local development, becomes dependent on the mock server. You have to ensure the mock server is up and running and ready to handle requests before you run your tests or start developing. From the technical perspective, you need to spawn the server process in time and in parallel to whichever other process depends on it. While it may not sound like a big deal, it is a price to pay for this approach nonetheless, especially compared to the zero runtime cost of request client- and an environment-based interception. **Drawback #4: No control over runtime behaviors** Since the mock server and your tests run in two separate processes, there isn’t a straightforward way to affect the mock’s behavior directly from the test. At this point, we need to recall that we’re using API mocking to _gain_ control over the network, so whenever that control suffers due to the implementation details of mocking, it automatically becomes a drawback. Imagine the following test: ```jsx it("renders a placeholder when the movie is not found", async () => { render(<Movies />) // Assert the correct UI... }) ``` The `<Movies/>` component always performs a `GET /movies` request, that’s what it’s designed to do. In order to emulate a 404 response from the mock server, we need to bake in a special logical branch into that route handler on the server. For example, by responding with a 404 when the client requests a certain movie ID: ```jsx // mock-server.js app.get("/movie/:id", (req, res) => { if (req.params.id === "abc-123") { return res.status(404).end() } // ...the happy path here. }) ``` Instead of collocating the network behavior with the immediate surface that needs it (the test), we’re pushing it to the mock server, which increases its complexity. Because that collocation is not evident, maintaining such case-specific logic on the server becomes challenging. I like putting it this way: ten tests adding per-test overrides are much more efficient than one server handler accounting for ten different scenarios. **Drawback #5: Shared test state.** When using the mock server approach, you usually spawn a single server for the entire test run. This makes the mock server a common dependency between all tests, and it becomes quite easy for it to introduce a shared state, resulting in flaky test results. Allow me to illustrate. ```jsx it("adds a new movie to my collection", async () => { render(<MovieDashboard />) await performSomeAction({ input: "OOPS!", }) }) it("lists all my movies in my collection", async () => { render(<Movies />) // ...assert the list of movies. }) ``` Imagine that the first test performs an unexpected action that crashes the mock server. Respectfully, that test will fail, indicating a problem. But here’s a pickle: the next test will also fail, despite there being nothing wrong with it. Whenever your test fails due to any other factor but the issue in the tested system, you’re getting an unreliable test. Now, what if there were a dozen tests in this test file? Or maybe a hundred? Pin-pointing the actual problematic test would suddenly become a time-consuming exercise. This happens because all the tests depend on a shared state, that state being the runtime of the mock server. Although this is not as evident as a more conventional shared state issue of multiple tests depending on a single mutable data, the shared state introduced by a test server bears the same consequences on the reliability of our test suites. --- ## Comparison Now that we are familiar with the main API mocking algorithms, let’s summarize and compare them. To keep this comparison more systematic, I’m going to use the following criteria: - **Request’s integrity**. Does this algorithm perform the request at all? - **System’s integrity**. Does it alter our system (e.g. makes it request different resources)? - **Runtime control**. Does it allow controlling different network behaviors from our tests/application runtime (e.g. introducing behavior overrides on a per-test basis)? - **Maintenance & scalability**. How feasible it is to maintain across different request clients and, generally, throughout the project’s life-cycle. | | | | | | ------------------------------------ | ------------------------- | ------------------------------ | ------------------------- | | | Client-based interception | Environment-based interception | Server-based interception | | Request’s integrity | ❌ | ❌ | ✅ | | System’s integrity | ❌ | ❌ | ❌ | | Runtime control (behavior overrides) | ✅ | ✅ | ❌ | | Maintenance & scalability | ❌ | ✅ | ❌ | We can see that environment-based interception hits the most boxes compared to alternatives. It doesn’t come as a surprise that this is the most common approach used to implement API mocking in the wild. Pretender, Nock, PollyJS, and almost any other API mocking library you can find utilize the environment to provide request-agnostic and maintainable mocking. That is not a bad approach in itself but it does come with a few disadvantages that I’ve talked about previously in this article. The request’s and system’s integrity are still crucial characteristics to consider if we wish to minimize the difference between the test and the production system. Historically, these points were overlooked since altering the system was either a technical limitation or a price to pay in order to make the mocking work in the first place. I’m really happy to say that is no longer the case, and we can, and already have API mocking solutions that can preserve the application’s integrity across the entire request journey. To make this pitch even more unbelievable, those solutions are based on standard APIs that are widely supported and have been around for years now. So, what are those exactly? ## The “perfect” approach Okay, I hope I got your attention at this point. But before I reveal the cards, let’s forget about all those approaches, benefits, and drawbacks for a moment. Instead, let’s just focus on how would we describe the “ideal” API mocking solution. When I sat down to brainstorm this very question in 2018, I came up with a list of criteria such a solution would meet: 1. It actually performs requests (no request client or environment stubs). 2. It allows requests to hit the same resources as in production (no system deviation). 3. It allows controlling network behaviors from the test or application runtime. 4. It has no runtime or build-time cost, and a minimal maintenance cost. 5. It allows reusing the same mocks across the entire stack (in tests, in local development, in Cypress, Playwright, Storybook, etc). Now, that does sound ambitious! We used some of these criteria in our comparison today but others, like reusability, we haven’t even mentioned yet. Nevertheless, I like starting from lists like this because they help me focus on what I _want_ and then see what would be the price for having that. At the first glance, the price to meet all those criteria seems insurmountable. And yet, I began researching the matter, poking around beaten paths but also directions that were rather… unconventional. Until, finally, I stumbled upon something. ## Service Worker API Turned out, there was a standard browser API that introduced seamless request interception to procure response caching. It was the [Service Worker API](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers). Briefly, the Service Worker API revolves around registering a *worker—*a JavaScript module that can intercept any outgoing traffic on the page. What makes this kind of interception unique is that it happens entirely on the network level of your browser _after_ the request gets performed and leaves your application’s context. To help you understand what a huge difference this makes, allow me to illustrate the same HTTP request journey and where a Service Worker gets to shine:  But the Service Worker API is designed for _caching_, and it would be quite a fit to bend it to the API mocking needs. From the worker controlling unrelated clients to the browser throwing away the worker on hard-reload—there are a lot of challenges to overcome before this API could be utilized for mocking. Needless to say, this is a time-consuming endeavor with no guarantee of success. Which is precisely why I went with it! ## In the next episode Next time, we will learn how Service Workers can be used for API mocking, talk about the challenges and blockers that imposes, and get a look at a library that has revolutionized API mocking in terms of system integrity and reusability of mocks. Meanwhile, [follow me on Twitter](https://twitter.com/kettanaito) where I post technical tips and tricks around testing in JavaScript and stir occasional discussion or two. See you in the next one! <ResourceWidget resource="understanding-api-mocking-next-part"/>
article
Now that we talked about the common [Request interception algorithms](https://egghead.io/blog/understanding-api-mocking-request-interception-algorithms), it’s time to dive deeper into Service Workers and whether they can be used to implement API mocking (spoiler: they can). <ResourceWidget resource="youre-currently-reading-a-series" /> I haven’t listed them in the previous article intentionally because, to my best knowledge, there aren’t many libraries out there using Service Workers for this exact purpose. But why is that so? What kind of challenges arise when you try to use workers to intercept requests? And is it even possible to solve each and every one of those challenges to get a functional API mocking solution? To answer all of those questions, we have to start from the beginning. ## What is a Service Worker? A Service Worker is an event-driven background task that can intercept outgoing requests in the browser, modify navigation, and cache responses. You have certainly heard about Service Workers in the context of Progressive Web Applications (PWA) because they enable essential user experience enhancements like fast client-side caching, offline-first applications, and push notifications. But, as we will learn, they can also be used for so much more. ### Service Worker usage Every browser ships with a [standardized API to declare Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API), and here’s what it looks like: ```jsx // worker.js // Create a "fetch" event listener in the Service Worker // that triggers every time a page makes an HTTP request. self.addEventListener('fetch', (event) => { const { request } = event event.respondWith(async () => { // Look up a cached response for this request. const cachedResponse = await caches.match(request) if (cachedResponse) { // Respond with a cached response if present. return cachedResponse } // Perform the request as-is. const response = await fetch(request) // Cache the copy of the original response. await cache.put(request, response.clone()) // Respond with the original response. return response }) }) ``` > `caches` is a global object available in the Service Worker’s scope. > That is an example of a basic Service Worker script for caching resources on the browser level. Now, on its own, that module won’t really do anything. We need to *register* that worker in our application for it to do its magic. ```jsx // app.js // Register a Service Worker script for this application. await navigator.serviceWorker.register('./worker.js') ``` > Note that the Service Worker registration is asynchronous. The browser needs to check if your worker is already registered, compare it to the running version to issue an update, or download the worker script and then register it if it’s a new worker. All that is because worker registrations *persist across page reloads* to guarantee a better caching experience. > Once the worker is registered, it starts *controlling* our application—it can intercept, alter, and resolve any asynchronous requests our application makes from that point onward. ### Service Worker runtime You may be wondering **when** and **where** a Service Worker handles requests. The core of any worker is the `fetch` event listener, which means that something up the chain will dispatch that event. That something is *the browser*. That’s right, the worker integrates directly into the browser, and the latter notifies it about any outgoing requests that happen on the page. Despite our application registering the worker, the worker script doesn’t run as a part of the application’s runtime. Instead, it runs *in parallel to it*.  > A high-level diagram of the Service Worker runtime. > This characteristic makes the request interception performed by the worker unique because it captures HTTP requests that *have already happened* and are pending in the browser to be handled by any controlling workers before being sent to the actual server. ## What if…? One of the main use cases for Service Workers is responding from the cache. However, that is not the only source for the responses you can send from the worker. You might have noticed that in the case of an uncached request, we are sending an original `Response` instance after fetching the resource: ```jsx // worker.js self.addEventListener('fetch', (event) => { event.respondWith(async () => { const response = await fetch(request) return response }) }) ``` In fact, the `event.respondWith()` function just expects a [Fetch API `Response` instance](https://developer.mozilla.org/en-US/docs/Web/API/Response) regardless of where we get it from, even if we construct a dummy response ourselves: ```jsx // worker.js self.addEventListener('fetch', (event) => { // Respond to every outgoing request with a dummy response. event.respondWith(new Response('Hello world!')) }) ``` > The cached responses stored in the global `caches` object are also plain `Response` instances! > And that custom response will be handled like any other HTTP response in the browser:  > A “Network” tab screenshot showcasing a custom `Response` instance sent over the network. > Wait, so there’s a standardized browser API to intercept requests on a network level and resolve them with arbitrary responses? That screams API mocking! ## Challenges Well, not that fast. While the Service Worker API is fantastic for many purposes, it wasn’t quite designed with API mocking in mind. There are a number of intricacies in the worker’s behavior that can put spokes in the wheel of our ambition. ### Service Worker life cycle If we decide to put the request matching logic in the worker, we would be modifying the worker script quite often. But here’s the thing: unless you disable this in the browser’s devtools, any changes to the worker script will only get applied on the next page load when your application’s code loads again and registers the modified worker. This can easily lead to stale mocking logic, resulting in unreliable tests or confusing development experience. Besides, any changes to the request matching logic, such as appending a new mock scenario for a specific test, would require a full page reload, which further degrades the DX. ### Hard-reloading Remember how I mentioned that workers persist between page reloads? Well, what if you want to opt-out from that? What if you’ve accidentally registered a worker with a bug? You would want to have that worker force-removed, and the specification comes with an escape hatch to allow you just that. You see, whenever you hard reload the page, the browser will forcefully unregister any active Service Worker controlling the page. So, if we implement API mocking using the worker, a hard reload will disable any mocking altogether until the next page reload. That is not ideal, to say the least because it can easily lead to unpredictable behavior both when developing and testing our application against mocks. ### Scope Any Service Worker registers at a specific scope (by default, its the worker’s location on the server and all nested child paths there). This is great for controlling cache from different parts of the application but not so great when it comes to API mocking. You see, the worker persists not only between page reloads but also between *browser sessions*.In other words, it gets registered in the browser and stays there until the same site either updates the worker or unregisters it. Given that a lot of applications are developed on the same [localhost](http://localhost) port, this would mean that a mock Service Worker would still affect the traffic between different projects if you decide to spin them up on the same port. That sounds like a recipe for confusion. ### Browser timeout Service Workers get terminated by the browser if they’ve been idle or too busy for too long. It would be rather unfortunate to lose the API mocking superpowers if you’ve been focusing on a different part of your application for some time. That time differs between browsers but most seem to implement the pruning of idle workers in one way or another. ## Mock Service Worker  Despite the challenges, five years ago I became interested in using Service Workers for API mocking. This led to an open-source library I created called [Mock Service Worker](https://github.com/mswjs/msw) (MSW). MSW has become one of the most widely used API mocking solutions in JavaScript, helping hundreds of thousands of developers prototype, debug, and test their products. It's even been adopted by companies like Google, Microsoft, Amazon, Vercel, and countless others to ensure network control in their CI pipelines. But MSW's innovation doesn't stop at its interception algorithm. The key design principles of the library are what really sets it apart from the rest. <EmailSubscribeWidget /> ### Key principles 🤝 **Seamless** From day one I wanted to build an API mocking solution that wouldn’t ask you to do any changes to your application. Not during tests, not ever. Let it request the same production resources but get mocked, defined responses back whenever you need them. Let it evaluate as much of your production code as physically possible, which meant no patching of `window.fetch` or meddling with the request clients your application may use, while still giving you full control over the network. 🌐 **Agnostic** Achieving that level of seamlessness requires being fully agnostic. MSW works equally well for any request clients, including `window.fetch`, Axios, React Query, or Apollo, without requiring configurations, adapters, or plugins. Moreover, MSW provides the same predictable behavior regardless of whether it is used in the browser or in Node.js. This environment-agnostic approach enables MSW to work seamlessly with any tooling that you may use while working on your project, including Storybook, Cypress, Playwright, Jest, Mocha, and more. ♻️ **Reusable** API mocking is often considered a feature of testing frameworks, but this significantly limits its capabilities. To fully benefit from API mocking, it should have its own layer in your application, separate from the tests and tools you use. This way, you can have a single source of truth for network behavior and integrate it wherever you need, giving you total control of your network across the entire stack. Simply describe mocks once and use them anywhere. ### Using Mock Service Worker Alright, that was a nice prep talk, how do you actually use the library? > While I will walk you through the library usage below, we have an official [Getting Started](https://mswjs.io/docs/getting-started) tutorial that I highly recommend reading while integrating MSW into your project. > ### 1. **Describe the network** We start by describing the network behavior we want by using *request handlers*. Those are functions that are responsible for two things: intercepting requests and resolving their responses. Think of them as of server-side route handlers because, effectively, you’re describing server-side behaviors when writing API mocks. Here’s an example of a `handlers.js` module that describes how to handle some requests: ```jsx // src/mocks/handlers.js import { rest, graphql } from 'msw' export const handlers = [ // This request handler describes how to process // a "GET /user" request. rest.get('/user', (req, res, ctx) => { return res(ctx.json({ firstName: 'John', age: 32 })) }), // In a similar fashion, this handler intercepts and resolves // GraphQL queries named "GetRecommendedMovies". graphql.query('GetRecommendedMovies', (req, res, ctx) => { return res( ctx.data({ movies: [ { id: 1, title: 'The Lord of the Rings' }, { id: 2, title: 'The Godfather' } ] }) ) }) ] ``` > MSW ships with first-class support for mocking GraphQL API! Say goodbye to mock providers and embrace silly-fast prototyping by combining multiple API types at the same time. > A module like `handlers.js` is a great place to put the “happy paths” of your applications—HTTP transactions applicable at any level of your app. We can add new handlers or change the existing ones later on via the `[.use()` API](https://mswjs.io/docs/api/setup-worker/use), both on browser runtime and on a per-test basis in Node.js. ### 2. **Integrate into environments** Notice how we didn’t take into account *where* our handlers will run or what request clients our application will be using. Because we don’t need any of those details to describe the network. Now, once it’s described, we can proceed with creating *integration points*. With MSW, you can integrate your network behavior with any browser and any Node.js process, including at the same time! **Browser integration** In the browser, MSW operates by registering and activating a Service Worker. Since Service Workers can intercept and affect outgoing traffic, it’s a security requirement that you host and serve the workers by yourself. The library ships with a handy CLI to help us copy the worker script into our application’s public directory: ```jsx npx msw init ./public ``` > Depending on the framework you’re using, that public directory may be different. Please consult your framework’s documentation to find the correct public directory path to use. > This will copy the `./mockServiceWorker.js` script into `./public`, so it’s publicly served from the application’s root. This step is only necessary when creating the browser integration. Next, we have to register that worker. The library exposes a handy `setupWorker` API to set up and automatically register the worker script we’ve just served: ```jsx // src/mocks/browser.js // 1. Import the "setupWorker" function that configures and registers // the Service Worker responsible for request interception. import { setupWorker } from 'msw' // 2. Import your "happy paths" handlers. import { handlers } from './handlers' // 3. Create a "worker" instance that you can later use // to enable mocking and change its behavior on runtime. export const worker = setupWorker(...handlers) ``` The `setupWorker` function configures the `worker` instance but doesn’t actually register anything yet. You can reuse the same worker instance across different browser processes, such as local development or an end-to-end test in tools like Cypress or Playwright. To actually register the worker and enable API mocking, we have to call the `.start()` method on the worker: ```jsx // src/App.jsx (or your application's root) // Conditionally start MSW. if (process.env.NODE_ENV === 'development') { const { worker } = require('./mocks/browser') worker.start() } ``` > Note that registering a Service Worker is an *asynchronous action*. Because of that, you may encounter a race condition between the worker’s registration and some of the requests your application performs on initial render. To account for those, I recommend [deferring your application’s render](https://mswjs.io/docs/recipes/deferred-mounting). > With this integration done, if we load our application in the browser, we will see a console message confirming that API mocking has been enabled:  Any outgoing requests that match the request handlers we’ve defined in `handlers.js` will be intercepted and resolved using the mocked responses we specified. You can observe the traffic in the “Network” tab in the devtools as you would do with real responses because, as far as your application is concerned, those *are* real responses. **Node.js integration** **There are no Service Workers in Node.js**. As the result of it, we don’t have to copy any scripts or account for any asynchronous registrations. Instead, MSW provides the `setupServer` API that has the same call signature as `setupWorker` but is meant to provision request interception by the means available in Node.js (I talked about those in the [Interception algorithms](https://egghead.io/blog/understanding-api-mocking-request-interception-algorithms) so feel free to learn more about those). ```jsx // src/mocks/node.js // 1. Import the "setupWorker" function and configures // the interception of requests in a Node.js process. import { setupServer } from 'msw/node' // 2. Import the same set of request handlers that describes // how the network should behave. import { handlers } from './handlers' // 3. Create a "server" instance that you can later use // to enable, modify, and disable API mocking. export const server = setupServer(...handlers) ``` > Note that despite the name, the `setupServer()` function doesn’t establish any servers. The name has been chosen for familiarity because, conceptually, you *are* describing a server-side behavior when using API mocking. > In a similar fashion, this configures the `server` instance to be reused across any Node.js processes (e.g. Node.js server development, testing frameworks like Vitest or Jest, React Native, etc). The remaining step is to enable the mocking by calling `server.listen()`. Below, you can see an example of integrating MSW in Vitest/Jest (which are Node.js processes running your tests): ```jsx // setupTests.js import { server } from './src/mocks/node' // Enable API mocking. beforeAll(() => server.listen()) // Make sure that request handlers we add on a per-test basis // are reset between tests. afterEach(() => server.resetHandlers()) // Clean up and disable API mocking. afterAll(() => server.close()) ``` > Learn more about the `setupServer` API in the [Documentation](https://mswjs.io/docs/api/setup-server). > ## Using Service Worker for API mocking At the beginning of this article I talked about how the Service Worker API isn’t designed for API mocking and that, despite its objective benefits, it poses a set of challenges to bend it to this particular use case. If that’s true, why am I advocating for this tool called MSW? Because it successfully solves those challenges and has been shipping an incredible mocking experience to developers for years now. Let’s dive into technical details on how exactly it did that. ### Writing mocks on the client In my first iteration of the library, I kept all the request handlers directly in the worker script. That has proven to be a bad decision on many levels: - You cannot use any third-party code. The worker’s scope is strict and you’d have to bundle the worker if you wish for it to include that code, which is an unnecessary overhead; - You cannot use your own application’s code, like utilities and helper functions, in the request handlers for the same reason as above; - Changes to the request handlers (i.e. to the worker) doesn’t apply on the page immediately. You have to wait for the worker update to be promoted, or check the “Update on reload” option in your browser’s devtools and still having to reload the page for the changes to take effect. Those are developer experience regressions I don’t wish to ship. Naturally, something has to be done about this, and the solution has once again led me to “use the platform”. I moved the request handlers (including the mocking logic) to the client side. This allows you to use your preferred languages, dependencies, and utilities to describe the network without burdening the worker. The entire request handling and response resolution pipeline is executed on the client, while the worker simply acts as an intermediary for captured requests and mocked responses. MSW establishes a `MessageChannel` between your application and the worker that allows the two to communicate effectively. Here’s how this approach translates to the HTTP request journey:  Notice that both the outgoing request (1) and the incoming response (3) are green, which means they are performed and received identically to production. Using a Service Worker means having no request client stubs *and* sending authentic responses from the network as if an actual server has sent them. This separation of concerns has clicked with me immediately because it provided me exactly what I was looking for: an interception algorithm that respects your application’s integrity. Moreover, by separating the concerns between the worker and the client, MSW is able to ship a snappy and reactive experience not affected by lazy worker updates or the worker’s life cycle phases. ### Handle hard reloading If you hard-reload the page, the browser will deactivate any workers controlling the current client. For MSW, that would mean deactivating any mocking and, potentially, breaking your app (e.g. when you’re developing mock-first). Luckily, there is a reliable way to detect when a hard reload happens specifically in the context of a worker. First, a bit of terminology: - A worker *registration* (obtainable by `navigator.serviceWorker.getRegistration()`) **is an entry kept by your browser that associates a particular client (e.g. a web page) with a particular Service Worker registration; - A *controller* (obtainable by `navigator.serviceWorker.controller`) points to the Service Worker instance that is currently controlling this client. When a hard reload happens, the browser forces the client to become uncontrolled (`navigator.serviceWorker.controller === null`). However, hard reload has no effect on the existing worker registrations. That’s why on the next (regular) reload of the page, the matching registration will activate the worker and promote it to become this client’s controller. Handling hard reload becomes a matter of detecting when that happens and forcing a regular page reload to skip the uncontrolled phase altogether: ```jsx const isControlled = navigator.serviceWorker.controller !== null const hasRegistration = await navigator.serviceWorker.getRegistration() .then(registration => typeof registration !== 'undefined') if (!isControlled && hasRegistration) { // If the client is uncontrolled but has registrations, // this indicates a hard reload. Force a regular reload // right afterward to promote the existing worker registration // to activate and control this client immediately. location.reload() } ``` ### Self-terminating Service Worker Now, when it comes to dealing with the worker’s scope, we certainly don’t want for one set of request handlers to leak to a completely different application served on the same local host. The way we handle this in MSW is by telling the library’s worker to unregister itself when the last controlled client is closed. This solution consists of two parts: 1. Client-side: Detecting when a controlled client is closed and signaling that to the worker; 2. Worker-side: When the number of clients reaches zero, unregister the worker. If you’ve used Service Workers before, you may know that you can unregister the worker from any controlled client by obtaining the worker reference and calling `worker.unregister()`. However, you can also do that *from the worker itself*. Here’s a rough example of the implementation for this solution: ```jsx // client.js document.addEventListener('beforeunload', () => { // Let the worker know that the current client is closing. worker.postMessage({ type: 'CLIENT_CLOSED' }) }) ``` ```jsx // mockServiceWorker.js const activeClients = new Set() self.addEventListener('message', async (event) => { const clientId = event.source.id if (event.data.type === 'CLIENT_CLOSED') { // Remove the closing client from the internal set. activeClients.remove(clientId) // If there are no more active clients left controlled // by this worker, unregister it. if (activeClients.size === 0) { self.registration.unregister() } } }) ``` Whenever you close the last page of your application, the worker will unregister itself. Opening a new application on the same host will have no worker present to control that host, giving us the clean state that we want. ### Keeping the worker alive While developing, you may not be touching API-related functionalities for some period of time, and the worker may become idle. To prevent the browser from unregistering such idle worker, MSW implements a pingpong messaging between the client and the worker so it constantly handles incoming events. ```jsx // client.js setInterval(() => { // Send a "PING" message to the worker every 5 seconds. worker.postMessage({ type: 'PING' }) }, 5_000) ``` ```jsx // mockService.Worker.js self.addEventListener('message', (event) => { // Whenever the client sends a "PING" message, // respond with a "PONG" message, keeping the worker busy. if (event.data.type === 'PING') { const clientId = event.source.id const client = await self.clients.get(clientId) const channel = new MessageChannel() client.postMessage({ type: 'PONG' }, [channel.port2]) } }) ``` ## Benefits The main benefit and also the main distinction of MSW is that it embraces API mocking as a standalone layer of your application. Mocks first, integrations later—that’s been the recipe that has unlocked previously unseen reusability where you don’t have to repeat yourself describing the same network behaviors across different tools that don’t understand each other. > And if you’d like to see how MSW compares to other solutions, we’ve got a [Comparison](https://mswjs.io/docs/comparison) page just for that. > With the option to reuse mocks and less amount of setup needed as a result, you aren’t just adding another library to your stack but investing into resilient, lasting solution that can support you from the early prototype to the finished product. Frameworks, languages, and libraries may come and go, and you wouldn’t have to make any changes to your API mocking layer (yes, I suggest you start calling it that!). If you’re still unconvinced, I highly recommend watching the [“Beyond API mocking” talk](https://www.youtube.com/watch?v=76yEzm07Kfk) by me and reading through the [“Stop mocking fetch” article](https://kentcdodds.com/blog/stop-mocking-fetch) by Kent C. Dodds. --- ## Closing thoughts MSW has already revolutionized the experience behind API mocking, and it will only push it forward with each release. Its features, such as behavior-driven network contracts, seamless integration, and the ability to alter your network as you please, are often taken for granted until you switch to another tool. I would like to finish this piece by saying thank you to Egghead for giving me this incredible opportunity to write about API mocking and MSW, in particular. And thank all of you for reading through this series, trying my projects out, giving feedback, and supporting me throughout the years. You are truly awesome, and I wish to share more exciting things with you in the months to come! If you believe in seamless, reusable API mocking that respects your application’s integrity, please consider supporting MSW on GitHub Sponsors at https://github.com/sponsors/mswjs. Every contribution helps us bring the future of API mocking closer to reality. Thank you! ## Links & materials - [**Official documentation**](https://mswjs.io) - [MSW on GitHub](https://github.com/mswjs/msw) - [MSW on Twitter](https://twitter.com/ApiMocking) - [Usage examples](https://github.com/mswjs/examples)
lessonDuration 1m 52s
The more your request handlers resemble the actual production behavior, the more confident you'll get when prototyping and testing with Mock Service Worker. But here's the thing—mocked responses arrive to the client **really quickly**. Learn how to control response timing and server-side latency by using the "delay" function. - [`delay()` API](https://mswjs.io/docs/api/delay)
lessonDuration 2m 2s
When mocking a collection of resources in Mock Service Worker, such as our movies, you will encounter requests that have dynamic parts in their URL, like `/movies/:slug`. In this lesson, learn how to use _path parameters_ to describe dynamic portions of the request's URL, access those parameters, and return a different response based on their values. - [Path parameters](https://mswjs.io/docs/network-behavior/rest#reading-path-parameters)
lessonDuration 2m 19s
Mocking authentication comes down to how it's implemented. With Mock Service Worker, you can mock the "Set-Cookie" response header to emulate a user session, but with Remix you don't even have to. Instead, in this lesson we will intercept only the authorization call to a database, leaving Remix to handle sessions, cookies, and auth state for us.
lessonDuration 1m 55s
Learn how to use the native `URL` and `URLSearchParams` classes to parse the intercepted request's URL and access its query parameters inside your Mock Service Worker handlers. - [Reading and writing request query parameters](https://mswjs.io/docs/recipes/query-parameters)
lessonDuration 1m 50s
Request handlers you write in Mock Service Worker apply for both Node.js and the browser simultaneously. In this lesson, you will handle a client-side request for movie recommendations using the same `http` namespace you already know. We will also take a sneak peek at the browser's Network to see what happens to the requests when we mock them.
lessonDuration 1m 47s
Let's use the "setupServer" API from Mock Service Worker to enable API mocking on the server-side of our Remix application. This way you can intercept and mock server-side requests, like those happening in the "loader" and "action" functions, as well as reuse the same setup for any other Node.js process, like integration tests with tools like Vitest or Jest in the future. - [Node.js integration](https://mswjs.io/docs/integrations/node)
lessonDuration 1m 33s
Error handling is crucial for a great user experience. Learn how to reproduce _any_ error response with Mock Service Worker, be it a 404, 500, or any other HTTP error response. - [Mocking error responses](https://mswjs.io/docs/basics/mocking-responses#mocking-error-responses)
lessonDuration 1m 34s
When working with existing APIs, especially those you don't own, being able to take the original response and manipulate it can be a life-changer when iterating on features or reproducing bugs. In this lesson, you will learn to perform the original request and then use Mock Service Worker to patch it with whichever data you want. - [`bypass()`](https://mswjs.io/docs/recipes/response-patching)
lessonDuration 3m 55s
Let's spice things up by adding GraphQL to our application. Since you are prototyping mock-first, you don't have to write any GraphQL schemas or define any resolvers. Instead, you will utilize Mock Service Worker to intercept valid GraphQL queries by their _type_ and _name_, and respond with the same semantic JSON responses matching the queries. - [Describing GraphQL APIs](http://mswjs.io/docs/network-behavior/graphql)
lessonDuration 2m 22sFree
You can send any data from your response resolvers. Let's implement a video streaming functionality by responding with a `ReadableStream` with Mock Service Worker. As a cherry on top, you will learn how to transform that video stream to inject server-side latency and see how our application's player handles it.
lessonDuration 3m 26sFree
Operation-based GraphQL mocking allows you to move fast without investing time into schemas or resolvers. But, when integrating Mock Service Worker into an existing application, going schema-first can be advantageous. Here's how you can route every GraphQL request to be resolved against a GraphQL schema, mocked or real, and use mock resolvers to control individual types and fields.
lessonDuration 1m 20s
Accounting for network errors is what makes a good application great. Unlike error responses, network errors represent issues when sending a request or receiving a response, but all the same can be mocked with standard JavaScript API. In this lesson, you will learn about `Response.error()` and how to use it to emulate network errors in your Mock Service Worker handlers. - [Network errors](http://mswjs.io/docs/basics/mocking-responses#mocking-network-errors)
lessonDuration 2m 15s
To control what happens to requests in Mock Service Worker, you need to intercept them first. Write your first **request handler** and learn how to intercept a server-side request our application makes in Remix's `loader`. And mocking a response? Using a Fetch API `Response` instance, of course! - [Describing RESTful APIs](http://mswjs.io/docs/network-behavior/rest)
lessonDuration 1m 4sFree
Hi! My name is [Artem](https://kettanaito.com). In this course, I will teach you how to mock REST and GraphQL APIs with [Mock Service Worker](https://mswjs.io). Together, we will build a movie streaming application and you will learn how to intercept both server-side and client-side requests and mock responses using standard JavaScript API. This is a state-of-the-art mock-first prototyping with MSW. - Join my [Discord server](https://kettanaito.com/discord) to go through the course with others, ask questions, and share feedback. See you there!
lessonDuration 20s
Before we begin, let's see how you can clone the Movie App repository from GitHub. This is not mandatory but will be helpful if you decide to follow along as we go through each lesson. - [Movie App on GitHub](https://github.com/kettanaito/movie-app)
lessonDuration 24s
Let's add `msw` to the project and prepare the basic directory structure with our `handlers.ts` where you will describe the network behavior you want.
lessonDuration 3m 28s
As the name implies, Mock Service Worker (MSW) uses the Service Worker API to intercept requests in the browser. By doing that, it can achieve API mocking without patching "fetch" or affecting the source code of your app in any way—all by using the platform. Learn how to copy the worker script and register the service worker to have API mocking enabled in for client-side development. - [Browser integration](https://mswjs.io/docs/integrations/browser)
lessonDuration 40s
Error responses in GraphQL are a bit unique. They must still produce a "200 OK" response and list the errors in the response body instead. Let's follow the GraphQL specification to produce a valid GraphQL error response in our Mock Service Worker handlers.
lessonDuration 1m
As you add more request handlers in Mock Service Worker, introducing a source of truth for the static data can help reduce the clutter and keep the network description focus on behavior instead of repeating fixtures. In this lesson, we will refactor our code by moving the static data outside and reusing it across existing request handlers.
lessonDuration 1m 6s
Mock Service Worker relies heavily on the standard Fetch API classes like Request and Response when describing the network. But sometimes standards aren't enough. For example, you cannot mock a response cookie because JavaScript prohibits setting the "Set-Cookie" header on a Response instance. Learn how to side-step this limitation by using a new "HttpResponse" class from MSW. - [`HttpResponse` API](https://mswjs.io/docs/api/http-response)