Mock Service Worker 2.0

Rate this content
Bookmark

It's been half a decade since Mock Service Worker (MSW) has changed the way developers approach and think of API mocking in JavaScript. With all its innovation, I felt we could do more. I spent the last year making that happen. I can't wait to share it with all of you!

This talk has been presented at TestJS Summit 2023, check out the latest edition of this JavaScript Conference.

FAQ

You can start using MSW by installing it via npm with the command `npm install msw`. For a more in-depth understanding, you can refer to the MSW documentation and explore courses like 'Mock REST and GraphQL APIs with Mock Service Worker'.

As of now, MSW does not natively support WebSockets. However, there are plans to explore this feature in the future.

MockServiceWorker (MSW) is an API mocking library that allows you to intercept requests and mock responses to control your network for testing, prototyping, and debugging purposes.

MSW introduces API mocking as a standalone layer, allowing you to describe your network once and integrate it into various testing tools. It avoids using window.fetch patches and relies on standard JavaScript APIs like the ServiceWorker API for browser-side interception.

Request handlers in MSW are functions that intercept specific network requests and produce mock responses. They allow you to define how the network request should be handled and what mock data should be returned.

Yes, MSW is written in TypeScript and provides native support for TypeScript, including generic support for request body, response body, URL parameters, and GraphQL queries and variables.

MSW is primarily used in integration tests and end-to-end tests to mock network interactions. However, it can also be used in unit tests if your unit requires network code.

Using MSW provides a shallow learning curve, better compatibility with other tools, less code to maintain, and an opportunity to get better at JavaScript by using standard APIs.

While there is no direct integration between MSW and Postman, it is theoretically possible to use them together by leveraging common data formats like HTTP Archives.

MSW 2.0 leverages the Fetch API as a common ground for both browser and Node.js environments, simplifying the API and making it more aligned with standard JavaScript practices.

Artem Zakharchenko
Artem Zakharchenko
27 min
07 Dec, 2023

Comments

Sign in or register to post your comment.

Video Summary and Transcription

MSW is an API mocking library that simplifies the process of intercepting requests and mocking responses. It leverages standard JavaScript APIs like the ServiceWorker API and the Fetch API. MSW has seen significant adoption, with over 90,000 projects on GitHub and 2.5 million weekly downloads on npm. The recent release of Node.js 18 has allowed for refactoring and simplification in MSW. MSW supports TypeScript and can be used for contract testing with tools like PACT I-O.
Available in Español: Mock Service Worker 2.0

1. Introduction to API Mocking with MSW

Short description:

Hello, everyone. Today, I would like to speak about API mocking, standards, JavaScript, and MockServiceWorker. MSW is an API mocking library that allows you to intercept requests and mock responses. It introduces API mocking as a standalone layer, solving the problem of repetitive network descriptions across different tools. MSW achieves API mocking without resorting to window.fetch patches, relying instead on the standard JavaScript API like ServiceWorker API.

Hello, everyone. It's a pleasure to be here and thank you for joining. Today, I would like to speak about API mocking, standards, JavaScript and, of course, MockServiceWorker.

First things first. My name is Artem. You can find me as Ketanaito pretty much everywhere, including my humble blog at ketanaito.com. And you may also know me as the author of MockServiceWorker.

Out of curiosity, can you raise your hand if you've heard about MSW? Wow, that's a lot. You will enjoy this talk. Yes, so for those who haven't heard about it, MSW is an API mocking library. So in essence, it allows you to intercept requests and mock responses, basically control your network for whichever it is you want, testing, prototyping, debugging.

And it has a bit of a unique approach to API mocking. It introduces API mocking as a standalone layer. So if you think about how you control your network during testing, for example, well, you have a bunch of these different tools, right? You have tools like Playwright and Cypress and Vitesse and Jest, and they all ship with their own API mocking capabilities, which are amazing. But the thing is, once you achieve this full test coverage of your product, you start to notice that this network descriptions you do, they kind of repeat. In essence, you just want to do one thing, describe the network, but you're using different APIs from different frameworks, and they don't know about each other. They can't communicate. It's very little you can reuse. And that's precisely what MSW solves. It lifts this intention up. So you have a single layer of your network description, and then you integrate it in particular tooling. And as a cherry on top, it achieves API mocking without resorting to this nasty window.fetch patches, and instead it relies on the standard JavaScript API, like ServiceWorker API, if we're speaking about the browser side interception.

But how do you do that? How do you describe the network with MSW? Well, you use these functions called request handlers. I will show you an example. So this is a very simple request handler. You can see that the intention here is to intercept a POST request to the slash user endpoint. And then we have this callback function that should produce the response. We have request, argument, response, and context. So what we're going to do with this request, we will try to read its body as JSON. So MSW will try to be smart here, actually, and see what content type header your request has.

2. API Mocking and JavaScript Improvements

Short description:

If it's application slash JSON, it will try to parse it and give you the object back. We use this REST composition function to compose a bunch of context utilities, like this context.json to return a JSON response. MSW marks its fifth anniversary this year. JavaScript has got a lot of improvements over the years. Frameworks like Next.js and Remix are ditching custom abstractions and betting more on JavaScript. MSW has over 90,000 projects on GitHub and more than 2.5 million downloads on npm every week.

And if it's application slash JSON, it will try to parse it and give you the object back. So we're accessing the name property here. And then to return a mock response, we use this REST composition function to compose a bunch of context utilities, like this context.json to return a JSON response. So this is a very, very basic example of your network description.

And one thing I like to do when using any third-party libraries, I like to do this fun exercise. So I take a very basic example like this one, and I remove everything that's not standard JavaScript. So let's do just that. Oh, not really much left. Basically all that was written there is still valid and functional, but it's all abstractions. If you think about it, REST.POST is an abstraction. It's something library-specific. The same as this call signature of response resolvers. Nowhere else in JavaScript do you use this call signature to handle requests. The response function, as much as I love functional composition, it's not as common in JavaScript, for better or worse. And, of course, the context utilities, a completely made-up API. And this API has been functional and working for years.

In fact, this year, I think, MSW marks its fifth anniversary. And you can say, well, if it's not broken, just don't fix it. Not a big fan of that. In fact, working in open source, I think, has taught me a much more important motive. If it's not educative, don't ship it. Because my goal as an open source maintainer is to share my ideas. But I also want all those developers that like my ideas and use my ideas to get better at JavaScript, at the language, not in my little projects. Because, if you think about it, JavaScript has got a lot of improvements over the years. And you can see this very apparently in the directions that frameworks like Next.js and Remix are taking. They're ditching those custom abstractions. And they're betting more and more on JavaScript because it's amazing. It just so happened that MSW has been used a lot. It has over 90,000 projects on GitHub alone using MSW. And more than 2.5 million downloads on npm every week.

QnA