Loading
Current section: Email 6 exercises
Problem

Mocking APIs with MSW and Testing

Loading exercise

Transcript

00:00 We don't want to hit the real Resend API during development or testing because that could potentially cost us money, and it makes things a little slower, and it requires an internet connection. So for all those reasons, we're going to make a mock. But we don't want to touch any of our source code. We want to try and do as many of the mocks as like a sidecar thing as possible.

00:19 So we're going to use a service or a library called MSW. That stands for Mock Service Worker. Now, it actually has nothing to do with server service workers the way that we're using it. It's just a node process that intercepts all of the fetch requests that we're going to be making, runs within our process, and will allow

00:39 us to handle things differently. So we'll kind of simulate the Resend API with our own mock handlers. And this is actually really awesome because it enables us to move faster and avoid the costs and everything else associated. So there are a couple of steps to this process,

00:57 though, because we don't want our mock server to be running in production. We want to actually talk to the real Resend API during production. And so we need to start up our server in a special mock mode. So we're going to be updating our dev server script. And we're going to update our init script

01:15 so that we can conditionally import the mock server and get the mock server started during development when we want to have mocks enabled. And then you're going to actually implement the mock itself. So you've got a couple of steps in here. Anytime you're making a change to the dev server start script or that index.js file, you're going to need to restart the server.

01:35 So stop the server, start it up again so that you can test out your changes there. And with that, I think you should have enough information to get going on this. So good luck.