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`