From c5004d42af89599932171d6842afd0468ab77225 Mon Sep 17 00:00:00 2001 From: Colin Ihrig Date: Sat, 17 Dec 2022 01:36:15 -0500 Subject: [PATCH] test_runner: run t.after() if test body throws This commit fixes a bug where t.after() was not called if the test body threw an exception. PR-URL: https://github.com/nodejs/node/pull/45870 Reviewed-By: Moshe Atlow Reviewed-By: Matteo Collina --- lib/internal/test_runner/test.js | 8 +++++++- test/message/test_runner_hooks.js | 7 +++++++ test/message/test_runner_hooks.out | 24 +++++++++++++++++++++--- 3 files changed, 35 insertions(+), 4 deletions(-) diff --git a/lib/internal/test_runner/test.js b/lib/internal/test_runner/test.js index 1570b9c55320e6..8b0ba16f1a6a79 100644 --- a/lib/internal/test_runner/test.js +++ b/lib/internal/test_runner/test.js @@ -508,6 +508,11 @@ class Test extends AsyncResource { } const { args, ctx } = this.getRunArgs(); + const after = runOnce(async () => { + if (this.hooks.after.length > 0) { + await this.runHook('after', { args, ctx }); + } + }); const afterEach = runOnce(async () => { if (this.parent?.hooks.afterEach.length > 0) { await this.parent.runHook('afterEach', { args, ctx }); @@ -549,10 +554,11 @@ class Test extends AsyncResource { return; } - await this.runHook('after', { args, ctx }); + await after(); await afterEach(); this.pass(); } catch (err) { + try { await after(); } catch { /* Ignore error. */ } try { await afterEach(); } catch { /* test is already failing, let's the error */ } if (isTestFailureError(err)) { if (err.failureType === kTestTimeoutFailure) { diff --git a/test/message/test_runner_hooks.js b/test/message/test_runner_hooks.js index e43fbd4ebf8922..dab607f862ff5f 100644 --- a/test/message/test_runner_hooks.js +++ b/test/message/test_runner_hooks.js @@ -142,3 +142,10 @@ test('afterEach throws and test fails', async (t) => { await t.test('1', () => { throw new Error('test'); }); await t.test('2', () => {}); }); + +test('t.after() is called if test body throws', (t) => { + t.after(() => { + t.diagnostic('- after() called'); + }); + throw new Error('bye'); +}); diff --git a/test/message/test_runner_hooks.out b/test/message/test_runner_hooks.out index e0b3e91b8c1376..6bb1705967d043 100644 --- a/test/message/test_runner_hooks.out +++ b/test/message/test_runner_hooks.out @@ -475,10 +475,28 @@ not ok 12 - afterEach throws and test fails error: '2 subtests failed' code: 'ERR_TEST_FAILURE' ... -1..12 -# tests 12 +# Subtest: t.after() is called if test body throws +not ok 13 - t.after() is called if test body throws + --- + duration_ms: * + failureType: 'testCodeFailure' + error: 'bye' + code: 'ERR_TEST_FAILURE' + stack: |- + * + * + * + * + * + * + * + * + ... +# - after() called +1..13 +# tests 13 # pass 2 -# fail 10 +# fail 11 # cancelled 0 # skipped 0 # todo 0