Loading
Current section: Network 7 exercises
solution

Response delay

Loading solution

Transcript

00:00 I will start by creating a test case for this scenario. So a new test, and I will use handles the request timeout as the title. In this test, I will add a new runtime handler, server.use for the same request, but here instead of resolving it in any way, I will force it to pend forever.

00:19 To do that, I will import a special function from MSW called delay. I will await it in this runtime request handler, right here, await delay. I will mark the resolver as a sync, and what this will do, delay will simply return me a timeout promise.

00:38 So instead of providing a specific duration of how much to pend, I will provide a special keyword called infinite. This will return the infinitely pending promise from this delay function. With this functionality, I will create a new variable called token promise and assign it the result of calling this auth token function.

00:57 I will grab the credentials from right here and have this promise ready. Notice that I will not await this promise just yet because before I do, I need to trigger that timeout logic. And for that, I need to advance time. So I'm actually marking date and time again here. So as I know, I will head to the test setup

01:17 and introduce the before all hook and call view use fake timers. And after all hook, where I will be use real timers to make the date and time marking possible. And now here, once I performed the token request, I will use the advanced timers by time and I will provide three seconds.

01:36 This is the same duration as this timeout promise duration right over here. And now finally, I'll be able to write an assertion that I expect this token promise to reject with an error that says request timed out. I will fix this typo, expect, and I will mark the whole test as asynchronous.

01:57 And now let's verify this by running NPM test and see our timeout test passing. So what's happening here is that whenever this request happens, MSW will cause it to pend forever. It will never resolve. And this allows our timeout promise to kick in because as the next step,

02:19 I'm advancing the timers, the mock date by three seconds, which is the exact duration of the timeout logic. And then I'm able to assert that this promise rejects with a timeout error.