Loading
Current section: Network 7 exercises
solution

Set up MSW

Loading solution

Transcript

00:00 Let's add an automated test for a getUserToken function to verify our MSW setup. We'll create a test file called getAuthToken.test.ts and quickly paste this little test here. What it does, it calls the getAuthToken function providing it with some credentials, but it doesn't even have any assertions just yet.

00:19 Now let me try running this test by npm test. I can see that the test is failing. That's because we're not handling any requests in our handlers just yet. But if I scroll above, that log message looks extremely familiar. Well, this is precisely the log from here, from our request handler, that prints the request method and request URL.

00:42 But how does MSW know that this request has happened? Let's go through it. So in our code, where we're making this request, our code will actually perform this fetch request and it will trigger MSW's interception algorithm. And since we have it enabled right here with server.listen in our Vitas setup,

00:59 it will start looking up for any matching handlers for this intercepted request. So it will see this first handler, which is matching because it matches all the methods to all the paths, and it will print this. It will execute this whole resolver, printing this console message in our test output. So as you see, we're able to trigger this request handler,

01:20 but it doesn't actually handle the request yet. Let's learn how to return a mock response in the next exercise.