From 28d1af603354e88bc022d4edf059ebd2f5a9b50a Mon Sep 17 00:00:00 2001 From: Moshe Atlow Date: Mon, 30 Mar 2026 12:15:07 +0300 Subject: [PATCH] test_runner: add `getTestContext()` --- doc/api/test.md | 38 +++++++++++++ lib/internal/test_runner/harness.js | 21 +++++++- lib/internal/test_runner/test.js | 2 + lib/test.js | 3 +- test/parallel/test-runner-get-test-context.js | 54 +++++++++++++++++++ 5 files changed, 116 insertions(+), 2 deletions(-) create mode 100644 test/parallel/test-runner-get-test-context.js diff --git a/doc/api/test.md b/doc/api/test.md index 257b17ae845f9c..ffb4ea3e37689d 100644 --- a/doc/api/test.md +++ b/doc/api/test.md @@ -3563,6 +3563,44 @@ Emitted when no more tests are queued for execution in watch mode. Emitted when one or more tests are restarted due to a file change in watch mode. +## `getTestContext()` + + + +* Returns: {TestContext|SuiteContext|undefined} + +Returns the [`TestContext`][] or [`SuiteContext`][] object associated with the +currently executing test or suite, or `undefined` if called outside of a test or +suite. This function can be used to access context information from within the +test or suite function or any async operations within them. + +```mjs +import { getTestContext } from 'node:test'; + +test('example test', async () => { + const ctx = getTestContext(); + console.log(`Running test: ${ctx.name}`); +}); + +describe('example suite', () => { + const ctx = getTestContext(); + console.log(`Running suite: ${ctx.name}`); +}); +``` + +When called from a test, returns a [`TestContext`][]. +When called from a suite, returns a [`SuiteContext`][]. + +If called from outside a test or suite (e.g., at the top level of a module or in +a setTimeout callback after execution has completed), this function returns +`undefined`. + +When called from within a hook (before, beforeEach, after, afterEach), this +function returns the context of the test or suite that the hook is associated +with. + ## Class: `TestContext`