1- // https://github.com/nodejs/node/blob/3e57891ee2fde0971e18fc383c25acf8f90def05 /lib/internal/test_runner/test.js
1+ // https://github.com/nodejs/node/blob/3759935ee29d8042d917d3ceaa768521c14413ff /lib/internal/test_runner/test.js
22
33'use strict'
44
@@ -43,7 +43,8 @@ const {
4343} = require ( '#internal/test_runner/utils' )
4444const {
4545 createDeferredPromise,
46- kEmptyObject
46+ kEmptyObject,
47+ once : runOnce
4748} = require ( '#internal/util' )
4849const { isPromise } = require ( '#internal/util/types' )
4950const {
@@ -486,8 +487,14 @@ class Test extends AsyncResource {
486487 return
487488 }
488489
490+ const { args, ctx } = this . getRunArgs ( )
491+ const afterEach = runOnce ( async ( ) => {
492+ if ( this . parent ?. hooks . afterEach . length > 0 ) {
493+ await this . parent [ kRunHook ] ( 'afterEach' , { args, ctx } )
494+ }
495+ } )
496+
489497 try {
490- const { args, ctx } = this . getRunArgs ( )
491498 if ( this . parent ?. hooks . beforeEach . length > 0 ) {
492499 await this . parent [ kRunHook ] ( 'beforeEach' , { args, ctx } )
493500 }
@@ -522,12 +529,10 @@ class Test extends AsyncResource {
522529 return
523530 }
524531
525- if ( this . parent ?. hooks . afterEach . length > 0 ) {
526- await this . parent [ kRunHook ] ( 'afterEach' , { args, ctx } )
527- }
528-
532+ await afterEach ( )
529533 this . pass ( )
530534 } catch ( err ) {
535+ try { await afterEach ( ) } catch { /* test is already failing, let's the error */ }
531536 if ( isTestFailureError ( err ) ) {
532537 if ( err . failureType === kTestTimeoutFailure ) {
533538 this . cancel ( err )
@@ -735,6 +740,12 @@ class Suite extends Test {
735740 }
736741
737742 async run ( ) {
743+ const hookArgs = this . getRunArgs ( )
744+ const afterEach = runOnce ( async ( ) => {
745+ if ( this . parent ?. hooks . afterEach . length > 0 ) {
746+ await this . parent [ kRunHook ] ( 'afterEach' , hookArgs )
747+ }
748+ } )
738749 try {
739750 this . parent . activeSubtests ++
740751 await this . buildSuite
@@ -746,8 +757,6 @@ class Suite extends Test {
746757 return
747758 }
748759
749- const hookArgs = this . getRunArgs ( )
750-
751760 if ( this . parent ?. hooks . beforeEach . length > 0 ) {
752761 await this . parent [ kRunHook ] ( 'beforeEach' , hookArgs )
753762 }
@@ -760,13 +769,11 @@ class Suite extends Test {
760769
761770 await SafePromiseRace ( [ promise , stopPromise ] )
762771 await this [ kRunHook ] ( 'after' , hookArgs )
763-
764- if ( this . parent ?. hooks . afterEach . length > 0 ) {
765- await this . parent [ kRunHook ] ( 'afterEach' , hookArgs )
766- }
772+ await afterEach ( )
767773
768774 this . pass ( )
769775 } catch ( err ) {
776+ try { await afterEach ( ) } catch { /* test is already failing, let's the error */ }
770777 if ( isTestFailureError ( err ) ) {
771778 this . fail ( err )
772779 } else {
0 commit comments