Loading
Current section: Network 7 exercises
solution

Error responses

Loading solution

Transcript

00:00 Let's start from refactoring our test setup so we're able to reference the same server object both in the setup and in individual tests. So I will take all the setup server call and its inputs and just move them to a different directory called mocks. In there I will create a module

00:16 called node.ts and paste them here. Since we also use handlers, let's move them from the root to this newly created mocks directory. That's it. And the last thing remaining is to export this server variable so we're able to reference it whenever we need. In fact let's go to vtest setup

00:33 and now import this server from mocks mocks slash node.ts and we will leave the rest of this setup vtest setup as it was before. Now let's try running our tests. So if I try running the tests

00:50 I will see that all these two error scenarios are failing because we're expecting the promise of get auth token to reject but it actually resolves with what looks like a successful response. That's precisely what's happening because all of them receive this successful response from

01:07 our base handlers. So what we want to do now is to go to individual tests and import the server. I'm going to import the server from the same directory mocks slash node.ts and I will head to this error case scenario and what I would do I would add a runtime request handler by calling

01:24 server.use. This use method supports a bunch of request handlers that will act as overwrites to your network behavior. So here I will create a matching handler for our post request using this

01:38 url as a path and in the resolver I'm going to respond by returning a 401 response the one we need to reproduce in order for this particular error to even happen when we call our function. Since we are creating this handler we also need this HTTP namespace I will import it from MSW.

02:01 Okay in a similar fashion let's create a runtime handler for another scenario where we are testing generic error handling by reproducing 500 responses. With this we can see that both successful happy path scenario and the error scenarios are passing

02:17 and notice that in the second case although we are testing an invalid input scenario the input itself doesn't matter because verifying its validity is the responsibility of the server. The responsibility of our get of token function is to properly handle a 401 response and that's

02:35 precisely what we're doing here we're always responding to this request with a 401 response so we're able to reproduce this error scenario in tests. Runtime handlers are extremely powerful because they allow you to provide network overrides on the test level while still

02:51 respecting the happy path scenarios like this first test which will respect your default handlers.ts array.