@@ -214,13 +214,31 @@ module.exports = function (app) {
214
214
: app
215
215
, obj = { } ;
216
216
217
+ var keepOpen = false
218
+ if ( typeof server !== 'string' && server && server . listen && server . address ) {
219
+ if ( ! server . address ( ) ) {
220
+ server = server . listen ( 0 )
221
+ }
222
+ }
223
+ obj . keepOpen = function ( ) {
224
+ keepOpen = true
225
+ return this
226
+ }
227
+ obj . close = function ( callback ) {
228
+ if ( server && server . close && keepOpen === false ) {
229
+ server . close ( callback ) ;
230
+ }
231
+ return this
232
+ }
217
233
methods . forEach ( function ( method ) {
218
234
obj [ method ] = function ( path ) {
219
- return new Test ( server , method , path ) ;
235
+ return new Test ( server , method , path )
236
+ . on ( 'end' , function ( ) {
237
+ obj . close ( ) ;
238
+ } ) ;
220
239
} ;
221
240
} ) ;
222
241
obj . del = obj . delete ;
223
-
224
242
return obj ;
225
243
} ;
226
244
@@ -257,8 +275,7 @@ function serverAddress (app, path) {
257
275
}
258
276
var addr = app . address ( ) ;
259
277
if ( ! addr ) {
260
- app . listen ( 0 ) ;
261
- addr = app . address ( ) ;
278
+ throw new Error ( 'Server is not listening' )
262
279
}
263
280
var protocol = ( app instanceof https . Server ) ? 'https' : 'http' ;
264
281
// If address is "unroutable" IPv4/6 address, then set to localhost
@@ -286,9 +303,22 @@ function TestAgent(app) {
286
303
if ( typeof app === 'function' ) app = http . createServer ( app ) ;
287
304
( Agent || Request ) . call ( this ) ;
288
305
this . app = app ;
306
+ if ( typeof app !== 'string' && app && app . listen && app . address && ! app . address ( ) ) {
307
+ this . app = app . listen ( 0 )
308
+ }
289
309
}
290
310
util . inherits ( TestAgent , Agent || Request ) ;
291
311
312
+ TestAgent . prototype . close = function close ( callback ) {
313
+ if ( this . app && this . app . close ) {
314
+ this . app . close ( callback )
315
+ }
316
+ return this
317
+ }
318
+ TestAgent . prototype . keepOpen = function keepOpen ( ) {
319
+ return this
320
+ }
321
+
292
322
// override HTTP verb methods
293
323
methods . forEach ( function ( method ) {
294
324
TestAgent . prototype [ method ] = function ( url ) {
0 commit comments