@@ -9,16 +9,26 @@ const FLUSH_DURATION = 200;
9
9
async function sleep ( ms : number ) : Promise < void > {
10
10
await new Promise ( resolve => setTimeout ( resolve , ms ) ) ;
11
11
}
12
-
12
+ /**
13
+ * Helper to prevent tests from ending before `flush()` has finished its work.
14
+ *
15
+ * This is necessary because, like its real-life counterpart, our mocked `res.send()` below doesn't await `res.end()
16
+ * (which becomes async when we wrap it in `withSentry` in order to give `flush()` time to run). In real life, the
17
+ * request/response cycle is held open as subsequent steps wait for `end()` to emit its `prefinished` event. Here in
18
+ * tests, without any of that other machinery, we have to hold it open ourselves.
19
+ *
20
+ * @param wrappedHandler
21
+ * @param req
22
+ * @param res
23
+ */
13
24
async function callWrappedHandler ( wrappedHandler : WrappedNextApiHandler , req : NextApiRequest , res : NextApiResponse ) {
14
25
await wrappedHandler ( req , res ) ;
15
26
16
- // Within the wrapped handler, we await `flush()` inside `res.end()`, but nothing awaits `res.end()`, because in its
17
- // original version, it's sync (unlike the function we wrap around it). The original does actually *act* like an async
18
- // function being awaited - subsequent steps in the request/response lifecycle don't happen until it emits a
19
- // `prefinished` event (which is why it's safe for us to make the switch). But here in tests, there's nothing past
20
- // `res.end()`, so we have to manually wait for it to be done.
27
+ // we know we need to wait at least this long for `flush()` to finish
21
28
await sleep ( FLUSH_DURATION ) ;
29
+
30
+ // should be <1 second, just long enough the `flush()` call to return, the original (pre-wrapping) `res.end()` to be
31
+ // called, and the response to be marked as done
22
32
while ( ! res . finished ) {
23
33
await sleep ( 100 ) ;
24
34
}
0 commit comments