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 Tech 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

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
This Talk introduces Test Effective Development, a new approach to testing that aims to make companies more cost-effective. The speaker shares their personal journey of improving code quality and reducing bugs through smarter testing strategies. They discuss the importance of finding a balance between testing confidence and efficiency and introduce the concepts of isolated and integrated testing. The speaker also suggests different testing strategies based on the size of the application and emphasizes the need to choose cost-effective testing approaches based on the specific project requirements.
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
This Talk discusses the challenges of testing in React and React Native applications, particularly with regards to barcode scanning. It explores the violation of separation of concerns in React and proposes the use of the HumbleObject model to simplify testing and improve code cleanliness. The MVP model is also introduced as a way to separate UI state and logic from the component. The importance of following patterns, standardization, and teaching principles is emphasized, along with the benefits of using custom hooks to share business logic. The potential of AI tools in code refactoring is mentioned as well.
We May Not Need Component Testing
Vue.js Live 2024Vue.js Live 2024
26 min
We May Not Need Component Testing
Component testing is a gray area between integration and unit testing. The demo app focuses on the cart component and writing test cases for Playwright component test and VTest. The first cart test encounters a bug with the invisible method in View Test.
Safely Handling Dynamic Data with TypeScript
Node Congress 2021Node Congress 2021
29 min
Safely Handling Dynamic Data with TypeScript
Top Content
This Talk discusses the safe handling of dynamic data with TypeScript using JSON Schema and TypeBox. Fastify, a web framework, allows developers to validate incoming data using JSON schema, providing type safety and error handling. TypeBox is a powerful library that allows developers to define JSON schemas and derive static types in TypeScript. The combination of JSON schema, TypeBox, and Fastify provides powerful tools for type safety and validation of dynamic data.
Component Testing With Vitest
TestJS Summit 2023TestJS Summit 2023
29 min
Component Testing With Vitest
This Talk explores the challenges of choosing and learning testing frameworks, emphasizing the importance of planning, automation, and prioritizing unit testing. The VTEST framework is introduced as a fast and stable option for unit testing JavaScript and TypeScript code, with a focus on logic and mocking external dependencies. The Talk also covers testing React hooks, integration testing with TestingLibraryReact, component testing, and achieving code coverage. Best practices include performing accessibility tests, planning tests before coding, and using data test IDs for stability.
Testing Vue 3 Applications with Mock Service Worker
Vue.js London 2023Vue.js London 2023
24 min
Testing Vue 3 Applications with Mock Service Worker
This Talk discusses testing V3 applications with Mock Service Worker, which is a library that allows simulating server responses in tests. It covers setting up Mock Service Worker by creating mock API responses and connecting it with the application. The Talk also explains how to write unit tests for asynchronous components using Vue's suspense component. It demonstrates how to test components that interact with APIs and handle error responses. Additionally, it mentions the testing library for components without API calls and emphasizes the importance of testing component interactions and API integration.

Workshops on related topic

Learn To Use Composables: The Swiss Army Knife Of Vue Developers
Vue.js Live 2024Vue.js Live 2024
163 min
Learn To Use Composables: The Swiss Army Knife Of Vue Developers
Workshop
Juan Andrés Núñez Charro
Juan Andrés Núñez Charro
Composables (composition functions) are stateful/stateless functions that can leverage Vue's reactivity API, decoupling it from components.This shift in perspective opens the possibility for tackling common scenarios in a new and creative way. In this workshop, you will learn how to solve typical problems every Vue developer faces, using composables:
- Data store;- Component cross-communication;- Utility functions (DOM, API, etc);And more.
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/