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!

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

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Test Effective Development
TestJS Summit 2021TestJS Summit 2021
31 min
Test Effective Development
Top Content
Developers want to sleep tight knowing they didn't break production. Companies want to be efficient in order to meet their customer needs faster and to gain competitive advantage sooner. We ALL want to be cost effective... or shall I say... TEST EFFECTIVE!But how do we do that?Are the "unit" and "integration" terminology serves us right?Or is it time for a change? When should we use either strategy to maximize our "test effectiveness"?In this talk I'll show you a brand new way to think about cost effective testing with new strategies and new testing terms!It’s time to go DEEPER!
The Art of ‘Humble Views’: Testing React Native Apps the Smart Way
TestJS Summit 2023TestJS Summit 2023
32 min
The Art of ‘Humble Views’: Testing React Native Apps the Smart Way
In this talk, we explore the divisive world of testing, where developers often find themselves torn between writing no tests and striving for 100% test coverage. Learn how to navigate these polarizing positions and adopt a more nuanced strategy that makes testing efficient and effective.We'll dive into the concept of 'Humble Views,' where we minimize untestable objects by extracting logic from UI elements into test-friendly parts of the codebase. This approach simplifies testing, focusing on business logic instead of UI complexities. Discover how the Model-View-Presenter (MVP) architecture helps achieve this, with presenters serving as a logical layer for testing and hooks aiding in separating logic from UI components.Throughout the talk, we'll discuss the trade-offs of this approach, the role of End-to-End (E2E) tests, and how to strike the perfect balance between too much and too little testing. Join us as we delve into the art of creating 'Humble Views,' ensuring that our React Native apps are scalable, maintainable, and effectively tested!
We May Not Need Component Testing
Vue.js Live 2024Vue.js Live 2024
26 min
We May Not Need Component Testing
Testings are mandatory and unit tests are the foundation for building a good testing system for our project. But for front end projects which involve components, how many unit tests are considered efficient and not overkill? Should we use additional libraries like Testing Library or Vue Test Utils with Vitest to test a component, when we can perform the same with just Playwright? Whether a component test using an E2E framework like Playwright is really a kill for? Let's find out in my talk.
Safely Handling Dynamic Data with TypeScript
Node Congress 2021Node Congress 2021
29 min
Safely Handling Dynamic Data with TypeScript
Top Content
TypeScript makes JavaScript safer adding static type definitions. Static definitions are wonderful; they prevent developers from making trivial mistakes ensuring every assignment and invocation is done correctly. A variable typed as a string cannot be assigned a number, and a function expecting three arguments cannot be called with only two. These definitions only exist at build time though; the code that is eventually executed is just JavaScript. But what about the response from an API request? In this talk Ethan Arrowood, Software Engineer 2 @ Microsoft, he will cover various solutions for safely typing dynamic data in TypeScript applications. This talk features popular technologies such as Fastify, JSON Schema, Node.js, and more!
Component Testing With Vitest
TestJS Summit 2023TestJS Summit 2023
29 min
Component Testing With Vitest
Testing is important. Proper unit tests can eliminate the chance for bugs to appear. But which testing framework will be suitable? Let’s explore how we can develop a reliable and efficient strategy for component development and testing with Vitest
Securing Node.js APIs with Decentralised Identity Tokens
JSNation Live 2021JSNation Live 2021
9 min
Securing Node.js APIs with Decentralised Identity Tokens
Authentication and Authorization are serious problems. We often dedicate a lot of time to craft powerful APIs but overlook proper security measures. Let's solve it with Magic using a key-based identity solution built on top of DID standard, where users’ identities are self-sovereign leveraging blockchain public-private key pairs. In this talk, we’ll look at proper ways to secure our Node.js APIs with Decentralised Identity Tokens. We’ll go from learning what Decentralised Identity standards are, how the users’ identities are self-sovereign leveraging blockchain public-private key pairs, why they’re the future of API security, and to put theory into practice we will build a real-world implementation using Node.js where I’ll show common best practices.

Workshops on related topic

Introduction to React Native Testing Library
React Advanced Conference 2022React Advanced Conference 2022
131 min
Introduction to React Native Testing Library
Workshop
Josh Justice
Josh Justice
Are you satisfied with your test suites? If you said no, you’re not alone—most developers aren’t. And testing in React Native is harder than on most platforms. How can you write JavaScript tests when the JS and native code are so intertwined? And what in the world are you supposed to do about that persistent act() warning? Faced with these challenges, some teams are never able to make any progress testing their React Native app, and others end up with tests that don’t seem to help and only take extra time to maintain.
But it doesn’t have to be this way. React Native Testing Library (RNTL) is a great library for component testing, and with the right mental model you can use it to implement tests that are low-cost and high-value. In this three-hour workshop you’ll learn the tools, techniques, and principles you need to implement tests that will help you ship your React Native app with confidence. You’ll walk away with a clear vision for the goal of your component tests and with techniques that will help you address any obstacle that gets in the way of that goal.you will know:- The different kinds React Native tests, and where component tests fit in- A mental model for thinking about the inputs and outputs of the components you test- Options for selecting text, image, and native code elements to verify and interact with them- The value of mocks and why they shouldn’t be avoided- The challenges with asynchrony in RNTL tests and how to handle them- Options for handling native functions and components in your JavaScript tests
Prerequisites:- Familiarity with building applications with React Native- Basic experience writing automated tests with Jest or another unit testing framework- You do not need any experience with React Native Testing Library- Machine setup: Node 16.x or 18.x, Yarn, be able to successfully create and run a new Expo app following the instructions on https://docs.expo.dev/get-started/create-a-new-app/