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.
Comments