@@ -10,6 +10,8 @@ import type { AddressInfo } from 'net';
10
10
import nock from 'nock' ;
11
11
import * as path from 'path' ;
12
12
13
+ const NODE_VERSION = parseSemver ( process . versions . node ) . major ;
14
+
13
15
export type TestServerConfig = {
14
16
url : string ;
15
17
server : http . Server ;
@@ -40,7 +42,6 @@ export type DataCollectorOptions = {
40
42
* @return {* } {jest.Describe}
41
43
*/
42
44
export const conditionalTest = ( allowedVersion : { min ?: number ; max ?: number } ) : jest . Describe => {
43
- const NODE_VERSION = parseSemver ( process . versions . node ) . major ;
44
45
if ( ! NODE_VERSION ) {
45
46
return describe . skip ;
46
47
}
@@ -127,6 +128,16 @@ export class TestEnv {
127
128
public constructor ( public readonly server : http . Server , public readonly url : string ) {
128
129
this . server = server ;
129
130
this . url = url ;
131
+
132
+ // We need to destroy the socket after the response has been sent
133
+ // to prevent the server.close (called inside nock interceptor) from hanging in tests.
134
+ // Otherwise the tests may timeout. (Happening on Node 20)
135
+ // See: https://github.com/nodejs/node/issues/2642
136
+ this . server . on ( 'request' , ( req , res ) => {
137
+ res . on ( 'finish' , ( ) => {
138
+ req . socket . end ( ) ;
139
+ } ) ;
140
+ } ) ;
130
141
}
131
142
132
143
/**
@@ -244,9 +255,7 @@ export class TestEnv {
244
255
// Ex: Remix scope bleed tests.
245
256
nock . cleanAll ( ) ;
246
257
247
- this . server . close ( ( ) => {
248
- resolve ( envelopes ) ;
249
- } ) ;
258
+ this . _closeServer ( ) ;
250
259
}
251
260
252
261
resolve ( envelopes ) ;
@@ -291,12 +300,19 @@ export class TestEnv {
291
300
292
301
nock . cleanAll ( ) ;
293
302
294
- this . server . close ( ( ) => {
295
- resolve ( reqCount ) ;
296
- } ) ;
297
-
303
+ this . _closeServer ( ) ;
298
304
resolve ( reqCount ) ;
299
305
} , options . timeout || 1000 ) ;
300
306
} ) ;
301
307
}
308
+
309
+ private _closeServer ( ) : void {
310
+ this . server . close ( ( ) => {
311
+ // @ts -ignore closeAllConnections() is only available from Node v18.2.0
312
+ if ( NODE_VERSION >= 18 && this . server . closeAllConnections ) {
313
+ // @ts -ignore (Only available in Node 18+)
314
+ this . server . closeAllConnections ( ) ;
315
+ }
316
+ } ) ;
317
+ }
302
318
}
0 commit comments