getTestContext()


返回与当前正在执行的测试或测试套件关联的 TestContextSuiteContext 对象,如果在测试或套件之外调用,则返回 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.

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}`);
}); 

当从测试中调用时,返回 TestContext。 当从套件中调用时,返回 SuiteContext

🌐 When called from a test, returns a TestContext. When called from a suite, returns a SuiteContext.

如果从测试或套件之外调用(例如,在模块的顶层或者在执行完成后的 setTimeout 回调中),此函数返回 undefined

🌐 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.

当从钩子函数(before、beforeEach、after、afterEach)内部调用时,该函数返回与该钩子相关的测试或测试套件的上下文。

🌐 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.