An instance of TestContext is passed to each test function in order to interact with the test runner. However, the TestContext constructor is not exposed as part of the API.
interface
test.default.TestContext
interface TestContext
- readonly assert: TestContextAssert
An object containing assertion methods bound to the test context. The top-level functions from the
node:assertmodule are exposed here for the purpose of creating test plans.Note: Some of the functions from
node:assertcontain type assertions. If these are called via the TestContextassertobject, then the context parameter in the test's function signature must be explicitly typed (ie. the parameter must have a type annotation), otherwise an error will be raised by the TypeScript compiler:import { test, type TestContext } from 'node:test'; // The test function's context parameter must have a type annotation. test('example', (t: TestContext) => { t.assert.deepStrictEqual(actual, expected); }); // Omitting the type annotation will result in a compilation error. test('example', t => { t.assert.deepStrictEqual(actual, expected); // Error: 't' needs an explicit type annotation. }); - readonly filePath: undefined | string
The absolute path of the test file that created the current test. If a test file imports additional modules that generate tests, the imported tests will return the path of the root test file.
- readonly signal: AbortSignal
test('top level test', async (t) => { await fetch('some/uri', { signal: t.signal }); }); - ): void;
This function is used to create a hook that runs after the current test finishes.
@param fnThe hook function. The first argument to this function is a
TestContextobject. If the hook uses callbacks, the callback function is passed as the second argument.@param optionsConfiguration options for the hook.
- ): void;
This function is used to create a hook running after each subtest of the current test.
@param fnThe hook function. The first argument to this function is a
TestContextobject. If the hook uses callbacks, the callback function is passed as the second argument.@param optionsConfiguration options for the hook.
- ): void;
This function is used to create a hook running before subtest of the current test.
@param fnThe hook function. The first argument to this function is a
TestContextobject. If the hook uses callbacks, the callback function is passed as the second argument.@param optionsConfiguration options for the hook.
- ): void;
This function is used to create a hook running before each subtest of the current test.
@param fnThe hook function. The first argument to this function is a
TestContextobject. If the hook uses callbacks, the callback function is passed as the second argument.@param optionsConfiguration options for the hook.
- message: string): void;
This function is used to write diagnostics to the output. Any diagnostic information is included at the end of the test's results. This function does not return a value.
test('top level test', (t) => { t.diagnostic('A diagnostic message'); });@param messageMessage to be reported.
- plan(count: number,): void;
This function is used to set the number of assertions and subtests that are expected to run within the test. If the number of assertions and subtests that run does not match the expected count, the test will fail.
Note: To make sure assertions are tracked,
t.assertmust be used instead ofassertdirectly.test('top level test', (t) => { t.plan(2); t.assert.ok('some relevant assertion here'); t.test('subtest', () => {}); });When working with asynchronous code, the
planfunction can be used to ensure that the correct number of assertions are run:test('planning with streams', (t, done) => { function* generate() { yield 'a'; yield 'b'; yield 'c'; } const expected = ['a', 'b', 'c']; t.plan(expected.length); const stream = Readable.from(generate()); stream.on('data', (chunk) => { t.assert.strictEqual(chunk, expected.shift()); }); stream.on('end', () => { done(); }); });When using the
waitoption, you can control how long the test will wait for the expected assertions. For example, setting a maximum wait time ensures that the test will wait for asynchronous assertions to complete within the specified timeframe:test('plan with wait: 2000 waits for async assertions', (t) => { t.plan(1, { wait: 2000 }); // Waits for up to 2 seconds for the assertion to complete. const asyncActivity = () => { setTimeout(() => { * t.assert.ok(true, 'Async assertion completed within the wait time'); }, 1000); // Completes after 1 second, within the 2-second wait time. }; asyncActivity(); // The test will pass because the assertion is completed in time. });Note: If a
waittimeout is specified, it begins counting down only after the test function finishes executing. - shouldRunOnlyTests: boolean): void;
If
shouldRunOnlyTestsis truthy, the test context will only run tests that have theonlyoption set. Otherwise, all tests are run. If Node.js was not started with the--test-onlycommand-line option, this function is a no-op.test('top level test', (t) => { // The test context can be set to run subtests with the 'only' option. t.runOnly(true); return Promise.all([ t.test('this subtest is now skipped'), t.test('this subtest is run', { only: true }), ]); });@param shouldRunOnlyTestsWhether or not to run
onlytests. - skip(message?: string): void;
This function causes the test's output to indicate the test as skipped. If
messageis provided, it is included in the output. Callingskip()does not terminate execution of the test function. This function does not return a value.test('top level test', (t) => { // Make sure to return here as well if the test contains additional logic. t.skip('this is skipped'); });@param messageOptional skip message.
- todo(message?: string): void;
This function adds a
TODOdirective to the test's output. Ifmessageis provided, it is included in the output. Callingtodo()does not terminate execution of the test function. This function does not return a value.test('top level test', (t) => { // This test is marked as `TODO` t.todo('this is a todo'); });@param messageOptional
TODOmessage. - condition: () => T,): Promise<Awaited<T>>;
This method polls a
conditionfunction until that function either returns successfully or the operation times out.@param conditionAn assertion function that is invoked periodically until it completes successfully or the defined polling timeout elapses. Successful completion is defined as not throwing or rejecting. This function does not accept any arguments, and is allowed to return any value.
@param optionsAn optional configuration object for the polling operation.
@returnsFulfilled with the value returned by
condition.