1# Test runner 2 3<!--introduced_in=v18.0.0--> 4 5<!-- YAML 6added: 7 - v18.0.0 8 - v16.17.0 9--> 10 11> Stability: 1 - Experimental 12 13<!-- source_link=lib/test.js --> 14 15The `node:test` module facilitates the creation of JavaScript tests. 16To access it: 17 18```mjs 19import test from 'node:test'; 20``` 21 22```cjs 23const test = require('node:test'); 24``` 25 26This module is only available under the `node:` scheme. The following will not 27work: 28 29```mjs 30import test from 'test'; 31``` 32 33```cjs 34const test = require('test'); 35``` 36 37Tests created via the `test` module consist of a single function that is 38processed in one of three ways: 39 401. A synchronous function that is considered failing if it throws an exception, 41 and is considered passing otherwise. 422. A function that returns a `Promise` that is considered failing if the 43 `Promise` rejects, and is considered passing if the `Promise` resolves. 443. A function that receives a callback function. If the callback receives any 45 truthy value as its first argument, the test is considered failing. If a 46 falsy value is passed as the first argument to the callback, the test is 47 considered passing. If the test function receives a callback function and 48 also returns a `Promise`, the test will fail. 49 50The following example illustrates how tests are written using the 51`test` module. 52 53```js 54test('synchronous passing test', (t) => { 55 // This test passes because it does not throw an exception. 56 assert.strictEqual(1, 1); 57}); 58 59test('synchronous failing test', (t) => { 60 // This test fails because it throws an exception. 61 assert.strictEqual(1, 2); 62}); 63 64test('asynchronous passing test', async (t) => { 65 // This test passes because the Promise returned by the async 66 // function is not rejected. 67 assert.strictEqual(1, 1); 68}); 69 70test('asynchronous failing test', async (t) => { 71 // This test fails because the Promise returned by the async 72 // function is rejected. 73 assert.strictEqual(1, 2); 74}); 75 76test('failing test using Promises', (t) => { 77 // Promises can be used directly as well. 78 return new Promise((resolve, reject) => { 79 setImmediate(() => { 80 reject(new Error('this will cause the test to fail')); 81 }); 82 }); 83}); 84 85test('callback passing test', (t, done) => { 86 // done() is the callback function. When the setImmediate() runs, it invokes 87 // done() with no arguments. 88 setImmediate(done); 89}); 90 91test('callback failing test', (t, done) => { 92 // When the setImmediate() runs, done() is invoked with an Error object and 93 // the test fails. 94 setImmediate(() => { 95 done(new Error('callback failure')); 96 }); 97}); 98``` 99 100If any tests fail, the process exit code is set to `1`. 101 102## Subtests 103 104The test context's `test()` method allows subtests to be created. This method 105behaves identically to the top level `test()` function. The following example 106demonstrates the creation of a top level test with two subtests. 107 108```js 109test('top level test', async (t) => { 110 await t.test('subtest 1', (t) => { 111 assert.strictEqual(1, 1); 112 }); 113 114 await t.test('subtest 2', (t) => { 115 assert.strictEqual(2, 2); 116 }); 117}); 118``` 119 120In this example, `await` is used to ensure that both subtests have completed. 121This is necessary because parent tests do not wait for their subtests to 122complete. Any subtests that are still outstanding when their parent finishes 123are cancelled and treated as failures. Any subtest failures cause the parent 124test to fail. 125 126## Skipping tests 127 128Individual tests can be skipped by passing the `skip` option to the test, or by 129calling the test context's `skip()` method as shown in the 130following example. 131 132```js 133// The skip option is used, but no message is provided. 134test('skip option', { skip: true }, (t) => { 135 // This code is never executed. 136}); 137 138// The skip option is used, and a message is provided. 139test('skip option with message', { skip: 'this is skipped' }, (t) => { 140 // This code is never executed. 141}); 142 143test('skip() method', (t) => { 144 // Make sure to return here as well if the test contains additional logic. 145 t.skip(); 146}); 147 148test('skip() method with message', (t) => { 149 // Make sure to return here as well if the test contains additional logic. 150 t.skip('this is skipped'); 151}); 152``` 153 154## `describe`/`it` syntax 155 156Running tests can also be done using `describe` to declare a suite 157and `it` to declare a test. 158A suite is used to organize and group related tests together. 159`it` is a shorthand for [`test()`][]. 160 161```js 162describe('A thing', () => { 163 it('should work', () => { 164 assert.strictEqual(1, 1); 165 }); 166 167 it('should be ok', () => { 168 assert.strictEqual(2, 2); 169 }); 170 171 describe('a nested thing', () => { 172 it('should work', () => { 173 assert.strictEqual(3, 3); 174 }); 175 }); 176}); 177``` 178 179`describe` and `it` are imported from the `node:test` module. 180 181```mjs 182import { describe, it } from 'node:test'; 183``` 184 185```cjs 186const { describe, it } = require('node:test'); 187``` 188 189## `only` tests 190 191If Node.js is started with the [`--test-only`][] command-line option, it is 192possible to skip all top level tests except for a selected subset by passing 193the `only` option to the tests that should be run. When a test with the `only` 194option set is run, all subtests are also run. The test context's `runOnly()` 195method can be used to implement the same behavior at the subtest level. 196 197```js 198// Assume Node.js is run with the --test-only command-line option. 199// The 'only' option is set, so this test is run. 200test('this test is run', { only: true }, async (t) => { 201 // Within this test, all subtests are run by default. 202 await t.test('running subtest'); 203 204 // The test context can be updated to run subtests with the 'only' option. 205 t.runOnly(true); 206 await t.test('this subtest is now skipped'); 207 await t.test('this subtest is run', { only: true }); 208 209 // Switch the context back to execute all tests. 210 t.runOnly(false); 211 await t.test('this subtest is now run'); 212 213 // Explicitly do not run these tests. 214 await t.test('skipped subtest 3', { only: false }); 215 await t.test('skipped subtest 4', { skip: true }); 216}); 217 218// The 'only' option is not set, so this test is skipped. 219test('this test is not run', () => { 220 // This code is not run. 221 throw new Error('fail'); 222}); 223``` 224 225## Filtering tests by name 226 227The [`--test-name-pattern`][] command-line option can be used to only run tests 228whose name matches the provided pattern. Test name patterns are interpreted as 229JavaScript regular expressions. The `--test-name-pattern` option can be 230specified multiple times in order to run nested tests. For each test that is 231executed, any corresponding test hooks, such as `beforeEach()`, are also 232run. 233 234Given the following test file, starting Node.js with the 235`--test-name-pattern="test [1-3]"` option would cause the test runner to execute 236`test 1`, `test 2`, and `test 3`. If `test 1` did not match the test name 237pattern, then its subtests would not execute, despite matching the pattern. The 238same set of tests could also be executed by passing `--test-name-pattern` 239multiple times (e.g. `--test-name-pattern="test 1"`, 240`--test-name-pattern="test 2"`, etc.). 241 242```js 243test('test 1', async (t) => { 244 await t.test('test 2'); 245 await t.test('test 3'); 246}); 247 248test('Test 4', async (t) => { 249 await t.test('Test 5'); 250 await t.test('test 6'); 251}); 252``` 253 254Test name patterns can also be specified using regular expression literals. This 255allows regular expression flags to be used. In the previous example, starting 256Node.js with `--test-name-pattern="/test [4-5]/i"` would match `Test 4` and 257`Test 5` because the pattern is case-insensitive. 258 259Test name patterns do not change the set of files that the test runner executes. 260 261## Extraneous asynchronous activity 262 263Once a test function finishes executing, the results are reported as quickly 264as possible while maintaining the order of the tests. However, it is possible 265for the test function to generate asynchronous activity that outlives the test 266itself. The test runner handles this type of activity, but does not delay the 267reporting of test results in order to accommodate it. 268 269In the following example, a test completes with two `setImmediate()` 270operations still outstanding. The first `setImmediate()` attempts to create a 271new subtest. Because the parent test has already finished and output its 272results, the new subtest is immediately marked as failed, and reported later 273to the {TestsStream}. 274 275The second `setImmediate()` creates an `uncaughtException` event. 276`uncaughtException` and `unhandledRejection` events originating from a completed 277test are marked as failed by the `test` module and reported as diagnostic 278warnings at the top level by the {TestsStream}. 279 280```js 281test('a test that creates asynchronous activity', (t) => { 282 setImmediate(() => { 283 t.test('subtest that is created too late', (t) => { 284 throw new Error('error1'); 285 }); 286 }); 287 288 setImmediate(() => { 289 throw new Error('error2'); 290 }); 291 292 // The test finishes after this line. 293}); 294``` 295 296## Watch mode 297 298<!-- YAML 299added: v18.13.0 300--> 301 302> Stability: 1 - Experimental 303 304The Node.js test runner supports running in watch mode by passing the `--watch` flag: 305 306```bash 307node --test --watch 308``` 309 310In watch mode, the test runner will watch for changes to test files and 311their dependencies. When a change is detected, the test runner will 312rerun the tests affected by the change. 313The test runner will continue to run until the process is terminated. 314 315## Running tests from the command line 316 317The Node.js test runner can be invoked from the command line by passing the 318[`--test`][] flag: 319 320```bash 321node --test 322``` 323 324By default, Node.js will recursively search the current directory for 325JavaScript source files matching a specific naming convention. Matching files 326are executed as test files. More information on the expected test file naming 327convention and behavior can be found in the [test runner execution model][] 328section. 329 330Alternatively, one or more paths can be provided as the final argument(s) to 331the Node.js command, as shown below. 332 333```bash 334node --test test1.js test2.mjs custom_test_dir/ 335``` 336 337In this example, the test runner will execute the files `test1.js` and 338`test2.mjs`. The test runner will also recursively search the 339`custom_test_dir/` directory for test files to execute. 340 341### Test runner execution model 342 343When searching for test files to execute, the test runner behaves as follows: 344 345* Any files explicitly provided by the user are executed. 346* If the user did not explicitly specify any paths, the current working 347 directory is recursively searched for files as specified in the following 348 steps. 349* `node_modules` directories are skipped unless explicitly provided by the 350 user. 351* If a directory named `test` is encountered, the test runner will search it 352 recursively for all all `.js`, `.cjs`, and `.mjs` files. All of these files 353 are treated as test files, and do not need to match the specific naming 354 convention detailed below. This is to accommodate projects that place all of 355 their tests in a single `test` directory. 356* In all other directories, `.js`, `.cjs`, and `.mjs` files matching the 357 following patterns are treated as test files: 358 * `^test$` - Files whose basename is the string `'test'`. Examples: 359 `test.js`, `test.cjs`, `test.mjs`. 360 * `^test-.+` - Files whose basename starts with the string `'test-'` 361 followed by one or more characters. Examples: `test-example.js`, 362 `test-another-example.mjs`. 363 * `.+[\.\-\_]test$` - Files whose basename ends with `.test`, `-test`, or 364 `_test`, preceded by one or more characters. Examples: `example.test.js`, 365 `example-test.cjs`, `example_test.mjs`. 366 * Other file types understood by Node.js such as `.node` and `.json` are not 367 automatically executed by the test runner, but are supported if explicitly 368 provided on the command line. 369 370Each matching test file is executed in a separate child process. If the child 371process finishes with an exit code of 0, the test is considered passing. 372Otherwise, the test is considered to be a failure. Test files must be 373executable by Node.js, but are not required to use the `node:test` module 374internally. 375 376Each test file is executed as if it was a regular script. That is, if the test 377file itself uses `node:test` to define tests, all of those tests will be 378executed within a single application thread, regardless of the value of the 379`concurrency` option of [`test()`][]. 380 381## Collecting code coverage 382 383When Node.js is started with the [`--experimental-test-coverage`][] 384command-line flag, code coverage is collected and statistics are reported once 385all tests have completed. If the [`NODE_V8_COVERAGE`][] environment variable is 386used to specify a code coverage directory, the generated V8 coverage files are 387written to that directory. Node.js core modules and files within 388`node_modules/` directories are not included in the coverage report. If 389coverage is enabled, the coverage report is sent to any [test reporters][] via 390the `'test:coverage'` event. 391 392Coverage can be disabled on a series of lines using the following 393comment syntax: 394 395```js 396/* node:coverage disable */ 397if (anAlwaysFalseCondition) { 398 // Code in this branch will never be executed, but the lines are ignored for 399 // coverage purposes. All lines following the 'disable' comment are ignored 400 // until a corresponding 'enable' comment is encountered. 401 console.log('this is never executed'); 402} 403/* node:coverage enable */ 404``` 405 406Coverage can also be disabled for a specified number of lines. After the 407specified number of lines, coverage will be automatically reenabled. If the 408number of lines is not explicitly provided, a single line is ignored. 409 410```js 411/* node:coverage ignore next */ 412if (anAlwaysFalseCondition) { console.log('this is never executed'); } 413 414/* node:coverage ignore next 3 */ 415if (anAlwaysFalseCondition) { 416 console.log('this is never executed'); 417} 418``` 419 420The test runner's code coverage functionality has the following limitations, 421which will be addressed in a future Node.js release: 422 423* Source maps are not supported. 424* Excluding specific files or directories from the coverage report is not 425 supported. 426 427## Mocking 428 429The `node:test` module supports mocking during testing via a top-level `mock` 430object. The following example creates a spy on a function that adds two numbers 431together. The spy is then used to assert that the function was called as 432expected. 433 434```mjs 435import assert from 'node:assert'; 436import { mock, test } from 'node:test'; 437 438test('spies on a function', () => { 439 const sum = mock.fn((a, b) => { 440 return a + b; 441 }); 442 443 assert.strictEqual(sum.mock.calls.length, 0); 444 assert.strictEqual(sum(3, 4), 7); 445 assert.strictEqual(sum.mock.calls.length, 1); 446 447 const call = sum.mock.calls[0]; 448 assert.deepStrictEqual(call.arguments, [3, 4]); 449 assert.strictEqual(call.result, 7); 450 assert.strictEqual(call.error, undefined); 451 452 // Reset the globally tracked mocks. 453 mock.reset(); 454}); 455``` 456 457```cjs 458'use strict'; 459const assert = require('node:assert'); 460const { mock, test } = require('node:test'); 461 462test('spies on a function', () => { 463 const sum = mock.fn((a, b) => { 464 return a + b; 465 }); 466 467 assert.strictEqual(sum.mock.calls.length, 0); 468 assert.strictEqual(sum(3, 4), 7); 469 assert.strictEqual(sum.mock.calls.length, 1); 470 471 const call = sum.mock.calls[0]; 472 assert.deepStrictEqual(call.arguments, [3, 4]); 473 assert.strictEqual(call.result, 7); 474 assert.strictEqual(call.error, undefined); 475 476 // Reset the globally tracked mocks. 477 mock.reset(); 478}); 479``` 480 481The same mocking functionality is also exposed on the [`TestContext`][] object 482of each test. The following example creates a spy on an object method using the 483API exposed on the `TestContext`. The benefit of mocking via the test context is 484that the test runner will automatically restore all mocked functionality once 485the test finishes. 486 487```js 488test('spies on an object method', (t) => { 489 const number = { 490 value: 5, 491 add(a) { 492 return this.value + a; 493 }, 494 }; 495 496 t.mock.method(number, 'add'); 497 assert.strictEqual(number.add.mock.calls.length, 0); 498 assert.strictEqual(number.add(3), 8); 499 assert.strictEqual(number.add.mock.calls.length, 1); 500 501 const call = number.add.mock.calls[0]; 502 503 assert.deepStrictEqual(call.arguments, [3]); 504 assert.strictEqual(call.result, 8); 505 assert.strictEqual(call.target, undefined); 506 assert.strictEqual(call.this, number); 507}); 508``` 509 510## Test reporters 511 512<!-- YAML 513added: v18.15.0 514changes: 515 - version: v18.17.0 516 pr-url: https://github.com/nodejs/node/pull/47238 517 description: Reporters are now exposed at `node:test/reporters`. 518--> 519 520The `node:test` module supports passing [`--test-reporter`][] 521flags for the test runner to use a specific reporter. 522 523The following built-reporters are supported: 524 525* `tap` 526 The `tap` reporter outputs the test results in the [TAP][] format. 527 528* `spec` 529 The `spec` reporter outputs the test results in a human-readable format. 530 531* `dot` 532 The `dot` reporter outputs the test results in a compact format, 533 where each passing test is represented by a `.`, 534 and each failing test is represented by a `X`. 535 536When `stdout` is a [TTY][], the `spec` reporter is used by default. 537Otherwise, the `tap` reporter is used by default. 538 539The reporters are available via the `node:test/reporters` module: 540 541```mjs 542import { tap, spec, dot } from 'node:test/reporters'; 543``` 544 545```cjs 546const { tap, spec, dot } = require('node:test/reporters'); 547``` 548 549### Custom reporters 550 551[`--test-reporter`][] can be used to specify a path to custom reporter. 552A custom reporter is a module that exports a value 553accepted by [stream.compose][]. 554Reporters should transform events emitted by a {TestsStream} 555 556Example of a custom reporter using {stream.Transform}: 557 558```mjs 559import { Transform } from 'node:stream'; 560 561const customReporter = new Transform({ 562 writableObjectMode: true, 563 transform(event, encoding, callback) { 564 switch (event.type) { 565 case 'test:start': 566 callback(null, `test ${event.data.name} started`); 567 break; 568 case 'test:pass': 569 callback(null, `test ${event.data.name} passed`); 570 break; 571 case 'test:fail': 572 callback(null, `test ${event.data.name} failed`); 573 break; 574 case 'test:plan': 575 callback(null, 'test plan'); 576 break; 577 case 'test:diagnostic': 578 callback(null, event.data.message); 579 break; 580 case 'test:coverage': { 581 const { totalLineCount } = event.data.summary.totals; 582 callback(null, `total line count: ${totalLineCount}\n`); 583 break; 584 } 585 } 586 }, 587}); 588 589export default customReporter; 590``` 591 592```cjs 593const { Transform } = require('node:stream'); 594 595const customReporter = new Transform({ 596 writableObjectMode: true, 597 transform(event, encoding, callback) { 598 switch (event.type) { 599 case 'test:start': 600 callback(null, `test ${event.data.name} started`); 601 break; 602 case 'test:pass': 603 callback(null, `test ${event.data.name} passed`); 604 break; 605 case 'test:fail': 606 callback(null, `test ${event.data.name} failed`); 607 break; 608 case 'test:plan': 609 callback(null, 'test plan'); 610 break; 611 case 'test:diagnostic': 612 callback(null, event.data.message); 613 break; 614 case 'test:coverage': { 615 const { totalLineCount } = event.data.summary.totals; 616 callback(null, `total line count: ${totalLineCount}\n`); 617 break; 618 } 619 } 620 }, 621}); 622 623module.exports = customReporter; 624``` 625 626Example of a custom reporter using a generator function: 627 628```mjs 629export default async function * customReporter(source) { 630 for await (const event of source) { 631 switch (event.type) { 632 case 'test:start': 633 yield `test ${event.data.name} started\n`; 634 break; 635 case 'test:pass': 636 yield `test ${event.data.name} passed\n`; 637 break; 638 case 'test:fail': 639 yield `test ${event.data.name} failed\n`; 640 break; 641 case 'test:plan': 642 yield 'test plan'; 643 break; 644 case 'test:diagnostic': 645 yield `${event.data.message}\n`; 646 break; 647 case 'test:coverage': { 648 const { totalLineCount } = event.data.summary.totals; 649 yield `total line count: ${totalLineCount}\n`; 650 break; 651 } 652 } 653 } 654} 655``` 656 657```cjs 658module.exports = async function * customReporter(source) { 659 for await (const event of source) { 660 switch (event.type) { 661 case 'test:start': 662 yield `test ${event.data.name} started\n`; 663 break; 664 case 'test:pass': 665 yield `test ${event.data.name} passed\n`; 666 break; 667 case 'test:fail': 668 yield `test ${event.data.name} failed\n`; 669 break; 670 case 'test:plan': 671 yield 'test plan\n'; 672 break; 673 case 'test:diagnostic': 674 yield `${event.data.message}\n`; 675 break; 676 case 'test:coverage': { 677 const { totalLineCount } = event.data.summary.totals; 678 yield `total line count: ${totalLineCount}\n`; 679 break; 680 } 681 } 682 } 683}; 684``` 685 686The value provided to `--test-reporter` should be a string like one used in an 687`import()` in JavaScript code. 688 689### Multiple reporters 690 691The [`--test-reporter`][] flag can be specified multiple times to report test 692results in several formats. In this situation 693it is required to specify a destination for each reporter 694using [`--test-reporter-destination`][]. 695Destination can be `stdout`, `stderr`, or a file path. 696Reporters and destinations are paired according 697to the order they were specified. 698 699In the following example, the `spec` reporter will output to `stdout`, 700and the `dot` reporter will output to `file.txt`: 701 702```bash 703node --test-reporter=spec --test-reporter=dot --test-reporter-destination=stdout --test-reporter-destination=file.txt 704``` 705 706When a single reporter is specified, the destination will default to `stdout`, 707unless a destination is explicitly provided. 708 709## `run([options])` 710 711<!-- YAML 712added: v18.9.0 713changes: 714 - version: v18.17.0 715 pr-url: https://github.com/nodejs/node/pull/47628 716 description: Add a testNamePatterns option. 717--> 718 719* `options` {Object} Configuration options for running tests. The following 720 properties are supported: 721 * `concurrency` {number|boolean} If a number is provided, 722 then that many test processes would run in parallel, where each process 723 corresponds to one test file. 724 If `true`, it would run `os.availableParallelism() - 1` test files in 725 parallel. 726 If `false`, it would only run one test file at a time. 727 **Default:** `false`. 728 * `files`: {Array} An array containing the list of files to run. 729 **Default** matching files from [test runner execution model][]. 730 * `inspectPort` {number|Function} Sets inspector port of test child process. 731 This can be a number, or a function that takes no arguments and returns a 732 number. If a nullish value is provided, each process gets its own port, 733 incremented from the primary's `process.debugPort`. 734 **Default:** `undefined`. 735 * `setup` {Function} A function that accepts the `TestsStream` instance 736 and can be used to setup listeners before any tests are run. 737 **Default:** `undefined`. 738 * `signal` {AbortSignal} Allows aborting an in-progress test execution. 739 * `testNamePatterns` {string|RegExp|Array} A String, RegExp or a RegExp Array, 740 that can be used to only run tests whose name matches the provided pattern. 741 Test name patterns are interpreted as JavaScript regular expressions. 742 For each test that is executed, any corresponding test hooks, such as 743 `beforeEach()`, are also run. 744 **Default:** `undefined`. 745 * `timeout` {number} A number of milliseconds the test execution will 746 fail after. 747 If unspecified, subtests inherit this value from their parent. 748 **Default:** `Infinity`. 749 * `watch` {boolean} Whether to run in watch mode or not. **Default:** `false`. 750* Returns: {TestsStream} 751 752```mjs 753import { tap } from 'node:test/reporters'; 754import process from 'node:process'; 755 756run({ files: [path.resolve('./tests/test.js')] }) 757 .compose(tap) 758 .pipe(process.stdout); 759``` 760 761```cjs 762const { tap } = require('node:test/reporters'); 763 764run({ files: [path.resolve('./tests/test.js')] }) 765 .compose(tap) 766 .pipe(process.stdout); 767``` 768 769## `test([name][, options][, fn])` 770 771<!-- YAML 772added: v18.0.0 773changes: 774 - version: v18.17.0 775 pr-url: https://github.com/nodejs/node/pull/47909 776 description: Added the `skip`, `todo`, and `only` shorthands. 777 - version: v18.8.0 778 pr-url: https://github.com/nodejs/node/pull/43554 779 description: Add a `signal` option. 780 - version: v18.7.0 781 pr-url: https://github.com/nodejs/node/pull/43505 782 description: Add a `timeout` option. 783--> 784 785* `name` {string} The name of the test, which is displayed when reporting test 786 results. **Default:** The `name` property of `fn`, or `'<anonymous>'` if `fn` 787 does not have a name. 788* `options` {Object} Configuration options for the test. The following 789 properties are supported: 790 * `concurrency` {number|boolean} If a number is provided, 791 then that many tests would run in parallel within the application thread. 792 If `true`, all scheduled asynchronous tests run concurrently within the 793 thread. If `false`, only one test runs at a time. 794 If unspecified, subtests inherit this value from their parent. 795 **Default:** `false`. 796 * `only` {boolean} If truthy, and the test context is configured to run 797 `only` tests, then this test will be run. Otherwise, the test is skipped. 798 **Default:** `false`. 799 * `signal` {AbortSignal} Allows aborting an in-progress test. 800 * `skip` {boolean|string} If truthy, the test is skipped. If a string is 801 provided, that string is displayed in the test results as the reason for 802 skipping the test. **Default:** `false`. 803 * `todo` {boolean|string} If truthy, the test marked as `TODO`. If a string 804 is provided, that string is displayed in the test results as the reason why 805 the test is `TODO`. **Default:** `false`. 806 * `timeout` {number} A number of milliseconds the test will fail after. 807 If unspecified, subtests inherit this value from their parent. 808 **Default:** `Infinity`. 809* `fn` {Function|AsyncFunction} The function under test. The first argument 810 to this function is a [`TestContext`][] object. If the test uses callbacks, 811 the callback function is passed as the second argument. **Default:** A no-op 812 function. 813* Returns: {Promise} Resolved with `undefined` once 814 the test completes, or immediately if the test runs within [`describe()`][]. 815 816The `test()` function is the value imported from the `test` module. Each 817invocation of this function results in reporting the test to the {TestsStream}. 818 819The `TestContext` object passed to the `fn` argument can be used to perform 820actions related to the current test. Examples include skipping the test, adding 821additional diagnostic information, or creating subtests. 822 823`test()` returns a `Promise` that resolves once the test completes. 824if `test()` is called within a `describe()` block, it resolve immediately. 825The return value can usually be discarded for top level tests. 826However, the return value from subtests should be used to prevent the parent 827test from finishing first and cancelling the subtest 828as shown in the following example. 829 830```js 831test('top level test', async (t) => { 832 // The setTimeout() in the following subtest would cause it to outlive its 833 // parent test if 'await' is removed on the next line. Once the parent test 834 // completes, it will cancel any outstanding subtests. 835 await t.test('longer running subtest', async (t) => { 836 return new Promise((resolve, reject) => { 837 setTimeout(resolve, 1000); 838 }); 839 }); 840}); 841``` 842 843The `timeout` option can be used to fail the test if it takes longer than 844`timeout` milliseconds to complete. However, it is not a reliable mechanism for 845canceling tests because a running test might block the application thread and 846thus prevent the scheduled cancellation. 847 848## `test.skip([name][, options][, fn])` 849 850Shorthand for skipping a test, 851same as [`test([name], { skip: true }[, fn])`][it options]. 852 853## `test.todo([name][, options][, fn])` 854 855Shorthand for marking a test as `TODO`, 856same as [`test([name], { todo: true }[, fn])`][it options]. 857 858## `test.only([name][, options][, fn])` 859 860Shorthand for marking a test as `only`, 861same as [`test([name], { only: true }[, fn])`][it options]. 862 863## `describe([name][, options][, fn])` 864 865* `name` {string} The name of the suite, which is displayed when reporting test 866 results. **Default:** The `name` property of `fn`, or `'<anonymous>'` if `fn` 867 does not have a name. 868* `options` {Object} Configuration options for the suite. 869 supports the same options as `test([name][, options][, fn])`. 870* `fn` {Function|AsyncFunction} The function under suite 871 declaring all subtests and subsuites. 872 The first argument to this function is a [`SuiteContext`][] object. 873 **Default:** A no-op function. 874* Returns: {Promise} Immediately fulfilled with `undefined`. 875 876The `describe()` function imported from the `node:test` module. Each 877invocation of this function results in the creation of a Subtest. 878After invocation of top level `describe` functions, 879all top level tests and suites will execute. 880 881## `describe.skip([name][, options][, fn])` 882 883Shorthand for skipping a suite, same as [`describe([name], { skip: true }[, fn])`][describe options]. 884 885## `describe.todo([name][, options][, fn])` 886 887Shorthand for marking a suite as `TODO`, same as 888[`describe([name], { todo: true }[, fn])`][describe options]. 889 890## `describe.only([name][, options][, fn])` 891 892<!-- YAML 893added: v18.15.0 894--> 895 896Shorthand for marking a suite as `only`, same as 897[`describe([name], { only: true }[, fn])`][describe options]. 898 899## `it([name][, options][, fn])` 900 901<!-- YAML 902added: 903 - v18.6.0 904 - v16.17.0 905changes: 906 - version: v18.16.0 907 pr-url: https://github.com/nodejs/node/pull/46889 908 description: Calling `it()` is now equivalent to calling `test()`. 909--> 910 911Shorthand for [`test()`][]. 912 913The `it()` function is imported from the `node:test` module. 914 915## `it.skip([name][, options][, fn])` 916 917Shorthand for skipping a test, 918same as [`it([name], { skip: true }[, fn])`][it options]. 919 920## `it.todo([name][, options][, fn])` 921 922Shorthand for marking a test as `TODO`, 923same as [`it([name], { todo: true }[, fn])`][it options]. 924 925## `it.only([name][, options][, fn])` 926 927<!-- YAML 928added: v18.15.0 929--> 930 931Shorthand for marking a test as `only`, 932same as [`it([name], { only: true }[, fn])`][it options]. 933 934## `before([fn][, options])` 935 936<!-- YAML 937added: v18.8.0 938--> 939 940* `fn` {Function|AsyncFunction} The hook function. 941 If the hook uses callbacks, 942 the callback function is passed as the second argument. **Default:** A no-op 943 function. 944* `options` {Object} Configuration options for the hook. The following 945 properties are supported: 946 * `signal` {AbortSignal} Allows aborting an in-progress hook. 947 * `timeout` {number} A number of milliseconds the hook will fail after. 948 If unspecified, subtests inherit this value from their parent. 949 **Default:** `Infinity`. 950 951This function is used to create a hook running before running a suite. 952 953```js 954describe('tests', async () => { 955 before(() => console.log('about to run some test')); 956 it('is a subtest', () => { 957 assert.ok('some relevant assertion here'); 958 }); 959}); 960``` 961 962## `after([fn][, options])` 963 964<!-- YAML 965added: v18.8.0 966--> 967 968* `fn` {Function|AsyncFunction} The hook function. 969 If the hook uses callbacks, 970 the callback function is passed as the second argument. **Default:** A no-op 971 function. 972* `options` {Object} Configuration options for the hook. The following 973 properties are supported: 974 * `signal` {AbortSignal} Allows aborting an in-progress hook. 975 * `timeout` {number} A number of milliseconds the hook will fail after. 976 If unspecified, subtests inherit this value from their parent. 977 **Default:** `Infinity`. 978 979This function is used to create a hook running after running a suite. 980 981```js 982describe('tests', async () => { 983 after(() => console.log('finished running tests')); 984 it('is a subtest', () => { 985 assert.ok('some relevant assertion here'); 986 }); 987}); 988``` 989 990## `beforeEach([fn][, options])` 991 992<!-- YAML 993added: v18.8.0 994--> 995 996* `fn` {Function|AsyncFunction} The hook function. 997 If the hook uses callbacks, 998 the callback function is passed as the second argument. **Default:** A no-op 999 function. 1000* `options` {Object} Configuration options for the hook. The following 1001 properties are supported: 1002 * `signal` {AbortSignal} Allows aborting an in-progress hook. 1003 * `timeout` {number} A number of milliseconds the hook will fail after. 1004 If unspecified, subtests inherit this value from their parent. 1005 **Default:** `Infinity`. 1006 1007This function is used to create a hook running 1008before each subtest of the current suite. 1009 1010```js 1011describe('tests', async () => { 1012 beforeEach(() => console.log('about to run a test')); 1013 it('is a subtest', () => { 1014 assert.ok('some relevant assertion here'); 1015 }); 1016}); 1017``` 1018 1019## `afterEach([fn][, options])` 1020 1021<!-- YAML 1022added: v18.8.0 1023--> 1024 1025* `fn` {Function|AsyncFunction} The hook function. 1026 If the hook uses callbacks, 1027 the callback function is passed as the second argument. **Default:** A no-op 1028 function. 1029* `options` {Object} Configuration options for the hook. The following 1030 properties are supported: 1031 * `signal` {AbortSignal} Allows aborting an in-progress hook. 1032 * `timeout` {number} A number of milliseconds the hook will fail after. 1033 If unspecified, subtests inherit this value from their parent. 1034 **Default:** `Infinity`. 1035 1036This function is used to create a hook running 1037after each subtest of the current test. 1038 1039```js 1040describe('tests', async () => { 1041 afterEach(() => console.log('finished running a test')); 1042 it('is a subtest', () => { 1043 assert.ok('some relevant assertion here'); 1044 }); 1045}); 1046``` 1047 1048## Class: `MockFunctionContext` 1049 1050<!-- YAML 1051added: v18.13.0 1052--> 1053 1054The `MockFunctionContext` class is used to inspect or manipulate the behavior of 1055mocks created via the [`MockTracker`][] APIs. 1056 1057### `ctx.calls` 1058 1059<!-- YAML 1060added: v18.13.0 1061--> 1062 1063* {Array} 1064 1065A getter that returns a copy of the internal array used to track calls to the 1066mock. Each entry in the array is an object with the following properties. 1067 1068* `arguments` {Array} An array of the arguments passed to the mock function. 1069* `error` {any} If the mocked function threw then this property contains the 1070 thrown value. **Default:** `undefined`. 1071* `result` {any} The value returned by the mocked function. 1072* `stack` {Error} An `Error` object whose stack can be used to determine the 1073 callsite of the mocked function invocation. 1074* `target` {Function|undefined} If the mocked function is a constructor, this 1075 field contains the class being constructed. Otherwise this will be 1076 `undefined`. 1077* `this` {any} The mocked function's `this` value. 1078 1079### `ctx.callCount()` 1080 1081<!-- YAML 1082added: v18.13.0 1083--> 1084 1085* Returns: {integer} The number of times that this mock has been invoked. 1086 1087This function returns the number of times that this mock has been invoked. This 1088function is more efficient than checking `ctx.calls.length` because `ctx.calls` 1089is a getter that creates a copy of the internal call tracking array. 1090 1091### `ctx.mockImplementation(implementation)` 1092 1093<!-- YAML 1094added: v18.13.0 1095--> 1096 1097* `implementation` {Function|AsyncFunction} The function to be used as the 1098 mock's new implementation. 1099 1100This function is used to change the behavior of an existing mock. 1101 1102The following example creates a mock function using `t.mock.fn()`, calls the 1103mock function, and then changes the mock implementation to a different function. 1104 1105```js 1106test('changes a mock behavior', (t) => { 1107 let cnt = 0; 1108 1109 function addOne() { 1110 cnt++; 1111 return cnt; 1112 } 1113 1114 function addTwo() { 1115 cnt += 2; 1116 return cnt; 1117 } 1118 1119 const fn = t.mock.fn(addOne); 1120 1121 assert.strictEqual(fn(), 1); 1122 fn.mock.mockImplementation(addTwo); 1123 assert.strictEqual(fn(), 3); 1124 assert.strictEqual(fn(), 5); 1125}); 1126``` 1127 1128### `ctx.mockImplementationOnce(implementation[, onCall])` 1129 1130<!-- YAML 1131added: v18.13.0 1132--> 1133 1134* `implementation` {Function|AsyncFunction} The function to be used as the 1135 mock's implementation for the invocation number specified by `onCall`. 1136* `onCall` {integer} The invocation number that will use `implementation`. If 1137 the specified invocation has already occurred then an exception is thrown. 1138 **Default:** The number of the next invocation. 1139 1140This function is used to change the behavior of an existing mock for a single 1141invocation. Once invocation `onCall` has occurred, the mock will revert to 1142whatever behavior it would have used had `mockImplementationOnce()` not been 1143called. 1144 1145The following example creates a mock function using `t.mock.fn()`, calls the 1146mock function, changes the mock implementation to a different function for the 1147next invocation, and then resumes its previous behavior. 1148 1149```js 1150test('changes a mock behavior once', (t) => { 1151 let cnt = 0; 1152 1153 function addOne() { 1154 cnt++; 1155 return cnt; 1156 } 1157 1158 function addTwo() { 1159 cnt += 2; 1160 return cnt; 1161 } 1162 1163 const fn = t.mock.fn(addOne); 1164 1165 assert.strictEqual(fn(), 1); 1166 fn.mock.mockImplementationOnce(addTwo); 1167 assert.strictEqual(fn(), 3); 1168 assert.strictEqual(fn(), 4); 1169}); 1170``` 1171 1172### `ctx.resetCalls()` 1173 1174<!-- YAML 1175added: v18.13.0 1176--> 1177 1178Resets the call history of the mock function. 1179 1180### `ctx.restore()` 1181 1182<!-- YAML 1183added: v18.13.0 1184--> 1185 1186Resets the implementation of the mock function to its original behavior. The 1187mock can still be used after calling this function. 1188 1189## Class: `MockTracker` 1190 1191<!-- YAML 1192added: v18.13.0 1193--> 1194 1195The `MockTracker` class is used to manage mocking functionality. The test runner 1196module provides a top level `mock` export which is a `MockTracker` instance. 1197Each test also provides its own `MockTracker` instance via the test context's 1198`mock` property. 1199 1200### `mock.fn([original[, implementation]][, options])` 1201 1202<!-- YAML 1203added: v18.13.0 1204--> 1205 1206* `original` {Function|AsyncFunction} An optional function to create a mock on. 1207 **Default:** A no-op function. 1208* `implementation` {Function|AsyncFunction} An optional function used as the 1209 mock implementation for `original`. This is useful for creating mocks that 1210 exhibit one behavior for a specified number of calls and then restore the 1211 behavior of `original`. **Default:** The function specified by `original`. 1212* `options` {Object} Optional configuration options for the mock function. The 1213 following properties are supported: 1214 * `times` {integer} The number of times that the mock will use the behavior of 1215 `implementation`. Once the mock function has been called `times` times, it 1216 will automatically restore the behavior of `original`. This value must be an 1217 integer greater than zero. **Default:** `Infinity`. 1218* Returns: {Proxy} The mocked function. The mocked function contains a special 1219 `mock` property, which is an instance of [`MockFunctionContext`][], and can 1220 be used for inspecting and changing the behavior of the mocked function. 1221 1222This function is used to create a mock function. 1223 1224The following example creates a mock function that increments a counter by one 1225on each invocation. The `times` option is used to modify the mock behavior such 1226that the first two invocations add two to the counter instead of one. 1227 1228```js 1229test('mocks a counting function', (t) => { 1230 let cnt = 0; 1231 1232 function addOne() { 1233 cnt++; 1234 return cnt; 1235 } 1236 1237 function addTwo() { 1238 cnt += 2; 1239 return cnt; 1240 } 1241 1242 const fn = t.mock.fn(addOne, addTwo, { times: 2 }); 1243 1244 assert.strictEqual(fn(), 2); 1245 assert.strictEqual(fn(), 4); 1246 assert.strictEqual(fn(), 5); 1247 assert.strictEqual(fn(), 6); 1248}); 1249``` 1250 1251### `mock.getter(object, methodName[, implementation][, options])` 1252 1253<!-- YAML 1254added: v18.13.0 1255--> 1256 1257This function is syntax sugar for [`MockTracker.method`][] with `options.getter` 1258set to `true`. 1259 1260### `mock.method(object, methodName[, implementation][, options])` 1261 1262<!-- YAML 1263added: v18.13.0 1264--> 1265 1266* `object` {Object} The object whose method is being mocked. 1267* `methodName` {string|symbol} The identifier of the method on `object` to mock. 1268 If `object[methodName]` is not a function, an error is thrown. 1269* `implementation` {Function|AsyncFunction} An optional function used as the 1270 mock implementation for `object[methodName]`. **Default:** The original method 1271 specified by `object[methodName]`. 1272* `options` {Object} Optional configuration options for the mock method. The 1273 following properties are supported: 1274 * `getter` {boolean} If `true`, `object[methodName]` is treated as a getter. 1275 This option cannot be used with the `setter` option. **Default:** false. 1276 * `setter` {boolean} If `true`, `object[methodName]` is treated as a setter. 1277 This option cannot be used with the `getter` option. **Default:** false. 1278 * `times` {integer} The number of times that the mock will use the behavior of 1279 `implementation`. Once the mocked method has been called `times` times, it 1280 will automatically restore the original behavior. This value must be an 1281 integer greater than zero. **Default:** `Infinity`. 1282* Returns: {Proxy} The mocked method. The mocked method contains a special 1283 `mock` property, which is an instance of [`MockFunctionContext`][], and can 1284 be used for inspecting and changing the behavior of the mocked method. 1285 1286This function is used to create a mock on an existing object method. The 1287following example demonstrates how a mock is created on an existing object 1288method. 1289 1290```js 1291test('spies on an object method', (t) => { 1292 const number = { 1293 value: 5, 1294 subtract(a) { 1295 return this.value - a; 1296 }, 1297 }; 1298 1299 t.mock.method(number, 'subtract'); 1300 assert.strictEqual(number.subtract.mock.calls.length, 0); 1301 assert.strictEqual(number.subtract(3), 2); 1302 assert.strictEqual(number.subtract.mock.calls.length, 1); 1303 1304 const call = number.subtract.mock.calls[0]; 1305 1306 assert.deepStrictEqual(call.arguments, [3]); 1307 assert.strictEqual(call.result, 2); 1308 assert.strictEqual(call.error, undefined); 1309 assert.strictEqual(call.target, undefined); 1310 assert.strictEqual(call.this, number); 1311}); 1312``` 1313 1314### `mock.reset()` 1315 1316<!-- YAML 1317added: v18.13.0 1318--> 1319 1320This function restores the default behavior of all mocks that were previously 1321created by this `MockTracker` and disassociates the mocks from the 1322`MockTracker` instance. Once disassociated, the mocks can still be used, but the 1323`MockTracker` instance can no longer be used to reset their behavior or 1324otherwise interact with them. 1325 1326After each test completes, this function is called on the test context's 1327`MockTracker`. If the global `MockTracker` is used extensively, calling this 1328function manually is recommended. 1329 1330### `mock.restoreAll()` 1331 1332<!-- YAML 1333added: v18.13.0 1334--> 1335 1336This function restores the default behavior of all mocks that were previously 1337created by this `MockTracker`. Unlike `mock.reset()`, `mock.restoreAll()` does 1338not disassociate the mocks from the `MockTracker` instance. 1339 1340### `mock.setter(object, methodName[, implementation][, options])` 1341 1342<!-- YAML 1343added: v18.13.0 1344--> 1345 1346This function is syntax sugar for [`MockTracker.method`][] with `options.setter` 1347set to `true`. 1348 1349## Class: `TestsStream` 1350 1351<!-- YAML 1352added: v18.9.0 1353--> 1354 1355* Extends {ReadableStream} 1356 1357A successful call to [`run()`][] method will return a new {TestsStream} 1358object, streaming a series of events representing the execution of the tests. 1359`TestsStream` will emit events, in the order of the tests definition 1360 1361### Event: `'test:coverage'` 1362 1363* `data` {Object} 1364 * `summary` {Object} An object containing the coverage report. 1365 * `files` {Array} An array of coverage reports for individual files. Each 1366 report is an object with the following schema: 1367 * `path` {string} The absolute path of the file. 1368 * `totalLineCount` {number} The total number of lines. 1369 * `totalBranchCount` {number} The total number of branches. 1370 * `totalFunctionCount` {number} The total number of functions. 1371 * `coveredLineCount` {number} The number of covered lines. 1372 * `coveredBranchCount` {number} The number of covered branches. 1373 * `coveredFunctionCount` {number} The number of covered functions. 1374 * `coveredLinePercent` {number} The percentage of lines covered. 1375 * `coveredBranchPercent` {number} The percentage of branches covered. 1376 * `coveredFunctionPercent` {number} The percentage of functions covered. 1377 * `uncoveredLineNumbers` {Array} An array of integers representing line 1378 numbers that are uncovered. 1379 * `totals` {Object} An object containing a summary of coverage for all 1380 files. 1381 * `totalLineCount` {number} The total number of lines. 1382 * `totalBranchCount` {number} The total number of branches. 1383 * `totalFunctionCount` {number} The total number of functions. 1384 * `coveredLineCount` {number} The number of covered lines. 1385 * `coveredBranchCount` {number} The number of covered branches. 1386 * `coveredFunctionCount` {number} The number of covered functions. 1387 * `coveredLinePercent` {number} The percentage of lines covered. 1388 * `coveredBranchPercent` {number} The percentage of branches covered. 1389 * `coveredFunctionPercent` {number} The percentage of functions covered. 1390 * `workingDirectory` {string} The working directory when code coverage 1391 began. This is useful for displaying relative path names in case the tests 1392 changed the working directory of the Node.js process. 1393 * `nesting` {number} The nesting level of the test. 1394 1395Emitted when code coverage is enabled and all tests have completed. 1396 1397### Event: `'test:dequeue'` 1398 1399* `data` {Object} 1400 * `file` {string|undefined} The path of the test file, 1401 `undefined` if test was run through the REPL. 1402 * `name` {string} The test name. 1403 * `nesting` {number} The nesting level of the test. 1404 1405Emitted when a test is dequeued, right before it is executed. 1406 1407### Event: `'test:diagnostic'` 1408 1409* `data` {Object} 1410 * `file` {string|undefined} The path of the test file, 1411 `undefined` if test was run through the REPL. 1412 * `message` {string} The diagnostic message. 1413 * `nesting` {number} The nesting level of the test. 1414 1415Emitted when [`context.diagnostic`][] is called. 1416 1417### Event: `'test:enqueue'` 1418 1419* `data` {Object} 1420 * `file` {string|undefined} The path of the test file, 1421 `undefined` if test was run through the REPL. 1422 * `name` {string} The test name. 1423 * `nesting` {number} The nesting level of the test. 1424 1425Emitted when a test is enqueued for execution. 1426 1427### Event: `'test:fail'` 1428 1429* `data` {Object} 1430 * `details` {Object} Additional execution metadata. 1431 * `duration` {number} The duration of the test in milliseconds. 1432 * `error` {Error} The error thrown by the test. 1433 * `file` {string|undefined} The path of the test file, 1434 `undefined` if test was run through the REPL. 1435 * `name` {string} The test name. 1436 * `nesting` {number} The nesting level of the test. 1437 * `testNumber` {number} The ordinal number of the test. 1438 * `todo` {string|boolean|undefined} Present if [`context.todo`][] is called 1439 * `skip` {string|boolean|undefined} Present if [`context.skip`][] is called 1440 1441Emitted when a test fails. 1442 1443### Event: `'test:pass'` 1444 1445* `data` {Object} 1446 * `details` {Object} Additional execution metadata. 1447 * `duration` {number} The duration of the test in milliseconds. 1448 * `file` {string|undefined} The path of the test file, 1449 `undefined` if test was run through the REPL. 1450 * `name` {string} The test name. 1451 * `nesting` {number} The nesting level of the test. 1452 * `testNumber` {number} The ordinal number of the test. 1453 * `todo` {string|boolean|undefined} Present if [`context.todo`][] is called 1454 * `skip` {string|boolean|undefined} Present if [`context.skip`][] is called 1455 1456Emitted when a test passes. 1457 1458### Event: `'test:plan'` 1459 1460* `data` {Object} 1461 * `file` {string|undefined} The path of the test file, 1462 `undefined` if test was run through the REPL. 1463 * `nesting` {number} The nesting level of the test. 1464 * `count` {number} The number of subtests that have ran. 1465 1466Emitted when all subtests have completed for a given test. 1467 1468### Event: `'test:start'` 1469 1470* `data` {Object} 1471 * `file` {string|undefined} The path of the test file, 1472 `undefined` if test was run through the REPL. 1473 * `name` {string} The test name. 1474 * `nesting` {number} The nesting level of the test. 1475 1476Emitted when a test starts reporting its own and its subtests status. 1477This event is guaranteed to be emitted in the same order as the tests are 1478defined. 1479 1480### Event: `'test:stderr'` 1481 1482* `data` {Object} 1483 * `file` {string} The path of the test file. 1484 * `message` {string} The message written to `stderr`. 1485 1486Emitted when a running test writes to `stderr`. 1487This event is only emitted if `--test` flag is passed. 1488 1489### Event: `'test:stdout'` 1490 1491* `data` {Object} 1492 * `file` {string} The path of the test file. 1493 * `message` {string} The message written to `stdout`. 1494 1495Emitted when a running test writes to `stdout`. 1496This event is only emitted if `--test` flag is passed. 1497 1498### Event: `'test:watch:drained'` 1499 1500Emitted when no more tests are queued for execution in watch mode. 1501 1502## Class: `TestContext` 1503 1504<!-- YAML 1505added: v18.0.0 1506changes: 1507 - version: v18.17.0 1508 pr-url: https://github.com/nodejs/node/pull/47586 1509 description: The `before` function was added to TestContext. 1510--> 1511 1512An instance of `TestContext` is passed to each test function in order to 1513interact with the test runner. However, the `TestContext` constructor is not 1514exposed as part of the API. 1515 1516### `context.before([fn][, options])` 1517 1518<!-- YAML 1519added: v18.17.0 1520--> 1521 1522* `fn` {Function|AsyncFunction} The hook function. The first argument 1523 to this function is a [`TestContext`][] object. If the hook uses callbacks, 1524 the callback function is passed as the second argument. **Default:** A no-op 1525 function. 1526* `options` {Object} Configuration options for the hook. The following 1527 properties are supported: 1528 * `signal` {AbortSignal} Allows aborting an in-progress hook. 1529 * `timeout` {number} A number of milliseconds the hook will fail after. 1530 If unspecified, subtests inherit this value from their parent. 1531 **Default:** `Infinity`. 1532 1533This function is used to create a hook running before 1534subtest of the current test. 1535 1536### `context.beforeEach([fn][, options])` 1537 1538<!-- YAML 1539added: v18.8.0 1540--> 1541 1542* `fn` {Function|AsyncFunction} The hook function. The first argument 1543 to this function is a [`TestContext`][] object. If the hook uses callbacks, 1544 the callback function is passed as the second argument. **Default:** A no-op 1545 function. 1546* `options` {Object} Configuration options for the hook. The following 1547 properties are supported: 1548 * `signal` {AbortSignal} Allows aborting an in-progress hook. 1549 * `timeout` {number} A number of milliseconds the hook will fail after. 1550 If unspecified, subtests inherit this value from their parent. 1551 **Default:** `Infinity`. 1552 1553This function is used to create a hook running 1554before each subtest of the current test. 1555 1556```js 1557test('top level test', async (t) => { 1558 t.beforeEach((t) => t.diagnostic(`about to run ${t.name}`)); 1559 await t.test( 1560 'This is a subtest', 1561 (t) => { 1562 assert.ok('some relevant assertion here'); 1563 }, 1564 ); 1565}); 1566``` 1567 1568### `context.after([fn][, options])` 1569 1570<!-- YAML 1571added: v18.13.0 1572--> 1573 1574* `fn` {Function|AsyncFunction} The hook function. The first argument 1575 to this function is a [`TestContext`][] object. If the hook uses callbacks, 1576 the callback function is passed as the second argument. **Default:** A no-op 1577 function. 1578* `options` {Object} Configuration options for the hook. The following 1579 properties are supported: 1580 * `signal` {AbortSignal} Allows aborting an in-progress hook. 1581 * `timeout` {number} A number of milliseconds the hook will fail after. 1582 If unspecified, subtests inherit this value from their parent. 1583 **Default:** `Infinity`. 1584 1585This function is used to create a hook that runs after the current test 1586finishes. 1587 1588```js 1589test('top level test', async (t) => { 1590 t.after((t) => t.diagnostic(`finished running ${t.name}`)); 1591 assert.ok('some relevant assertion here'); 1592}); 1593``` 1594 1595### `context.afterEach([fn][, options])` 1596 1597<!-- YAML 1598added: v18.8.0 1599--> 1600 1601* `fn` {Function|AsyncFunction} The hook function. The first argument 1602 to this function is a [`TestContext`][] object. If the hook uses callbacks, 1603 the callback function is passed as the second argument. **Default:** A no-op 1604 function. 1605* `options` {Object} Configuration options for the hook. The following 1606 properties are supported: 1607 * `signal` {AbortSignal} Allows aborting an in-progress hook. 1608 * `timeout` {number} A number of milliseconds the hook will fail after. 1609 If unspecified, subtests inherit this value from their parent. 1610 **Default:** `Infinity`. 1611 1612This function is used to create a hook running 1613after each subtest of the current test. 1614 1615```js 1616test('top level test', async (t) => { 1617 t.afterEach((t) => t.diagnostic(`finished running ${t.name}`)); 1618 await t.test( 1619 'This is a subtest', 1620 (t) => { 1621 assert.ok('some relevant assertion here'); 1622 }, 1623 ); 1624}); 1625``` 1626 1627### `context.diagnostic(message)` 1628 1629<!-- YAML 1630added: v18.0.0 1631--> 1632 1633* `message` {string} Message to be reported. 1634 1635This function is used to write diagnostics to the output. Any diagnostic 1636information is included at the end of the test's results. This function does 1637not return a value. 1638 1639```js 1640test('top level test', (t) => { 1641 t.diagnostic('A diagnostic message'); 1642}); 1643``` 1644 1645### `context.name` 1646 1647<!-- YAML 1648added: v18.8.0 1649--> 1650 1651The name of the test. 1652 1653### `context.runOnly(shouldRunOnlyTests)` 1654 1655<!-- YAML 1656added: v18.0.0 1657--> 1658 1659* `shouldRunOnlyTests` {boolean} Whether or not to run `only` tests. 1660 1661If `shouldRunOnlyTests` is truthy, the test context will only run tests that 1662have the `only` option set. Otherwise, all tests are run. If Node.js was not 1663started with the [`--test-only`][] command-line option, this function is a 1664no-op. 1665 1666```js 1667test('top level test', (t) => { 1668 // The test context can be set to run subtests with the 'only' option. 1669 t.runOnly(true); 1670 return Promise.all([ 1671 t.test('this subtest is now skipped'), 1672 t.test('this subtest is run', { only: true }), 1673 ]); 1674}); 1675``` 1676 1677### `context.signal` 1678 1679<!-- YAML 1680added: v18.7.0 1681--> 1682 1683* {AbortSignal} Can be used to abort test subtasks when the test has been 1684 aborted. 1685 1686```js 1687test('top level test', async (t) => { 1688 await fetch('some/uri', { signal: t.signal }); 1689}); 1690``` 1691 1692### `context.skip([message])` 1693 1694<!-- YAML 1695added: v18.0.0 1696--> 1697 1698* `message` {string} Optional skip message. 1699 1700This function causes the test's output to indicate the test as skipped. If 1701`message` is provided, it is included in the output. Calling `skip()` does 1702not terminate execution of the test function. This function does not return a 1703value. 1704 1705```js 1706test('top level test', (t) => { 1707 // Make sure to return here as well if the test contains additional logic. 1708 t.skip('this is skipped'); 1709}); 1710``` 1711 1712### `context.todo([message])` 1713 1714<!-- YAML 1715added: v18.0.0 1716--> 1717 1718* `message` {string} Optional `TODO` message. 1719 1720This function adds a `TODO` directive to the test's output. If `message` is 1721provided, it is included in the output. Calling `todo()` does not terminate 1722execution of the test function. This function does not return a value. 1723 1724```js 1725test('top level test', (t) => { 1726 // This test is marked as `TODO` 1727 t.todo('this is a todo'); 1728}); 1729``` 1730 1731### `context.test([name][, options][, fn])` 1732 1733<!-- YAML 1734added: v18.0.0 1735changes: 1736 - version: v18.8.0 1737 pr-url: https://github.com/nodejs/node/pull/43554 1738 description: Add a `signal` option. 1739 - version: v18.7.0 1740 pr-url: https://github.com/nodejs/node/pull/43505 1741 description: Add a `timeout` option. 1742--> 1743 1744* `name` {string} The name of the subtest, which is displayed when reporting 1745 test results. **Default:** The `name` property of `fn`, or `'<anonymous>'` if 1746 `fn` does not have a name. 1747* `options` {Object} Configuration options for the subtest. The following 1748 properties are supported: 1749 * `concurrency` {number|boolean|null} If a number is provided, 1750 then that many tests would run in parallel within the application thread. 1751 If `true`, it would run all subtests in parallel. 1752 If `false`, it would only run one test at a time. 1753 If unspecified, subtests inherit this value from their parent. 1754 **Default:** `null`. 1755 * `only` {boolean} If truthy, and the test context is configured to run 1756 `only` tests, then this test will be run. Otherwise, the test is skipped. 1757 **Default:** `false`. 1758 * `signal` {AbortSignal} Allows aborting an in-progress test. 1759 * `skip` {boolean|string} If truthy, the test is skipped. If a string is 1760 provided, that string is displayed in the test results as the reason for 1761 skipping the test. **Default:** `false`. 1762 * `todo` {boolean|string} If truthy, the test marked as `TODO`. If a string 1763 is provided, that string is displayed in the test results as the reason why 1764 the test is `TODO`. **Default:** `false`. 1765 * `timeout` {number} A number of milliseconds the test will fail after. 1766 If unspecified, subtests inherit this value from their parent. 1767 **Default:** `Infinity`. 1768* `fn` {Function|AsyncFunction} The function under test. The first argument 1769 to this function is a [`TestContext`][] object. If the test uses callbacks, 1770 the callback function is passed as the second argument. **Default:** A no-op 1771 function. 1772* Returns: {Promise} Resolved with `undefined` once the test completes. 1773 1774This function is used to create subtests under the current test. This function 1775behaves in the same fashion as the top level [`test()`][] function. 1776 1777```js 1778test('top level test', async (t) => { 1779 await t.test( 1780 'This is a subtest', 1781 { only: false, skip: false, concurrency: 1, todo: false }, 1782 (t) => { 1783 assert.ok('some relevant assertion here'); 1784 }, 1785 ); 1786}); 1787``` 1788 1789## Class: `SuiteContext` 1790 1791<!-- YAML 1792added: v18.7.0 1793--> 1794 1795An instance of `SuiteContext` is passed to each suite function in order to 1796interact with the test runner. However, the `SuiteContext` constructor is not 1797exposed as part of the API. 1798 1799### `context.name` 1800 1801<!-- YAML 1802added: v18.8.0 1803--> 1804 1805The name of the suite. 1806 1807### `context.signal` 1808 1809<!-- YAML 1810added: v18.7.0 1811--> 1812 1813* {AbortSignal} Can be used to abort test subtasks when the test has been 1814 aborted. 1815 1816[TAP]: https://testanything.org/ 1817[TTY]: tty.md 1818[`--experimental-test-coverage`]: cli.md#--experimental-test-coverage 1819[`--test-name-pattern`]: cli.md#--test-name-pattern 1820[`--test-only`]: cli.md#--test-only 1821[`--test-reporter-destination`]: cli.md#--test-reporter-destination 1822[`--test-reporter`]: cli.md#--test-reporter 1823[`--test`]: cli.md#--test 1824[`MockFunctionContext`]: #class-mockfunctioncontext 1825[`MockTracker.method`]: #mockmethodobject-methodname-implementation-options 1826[`MockTracker`]: #class-mocktracker 1827[`NODE_V8_COVERAGE`]: cli.md#node_v8_coveragedir 1828[`SuiteContext`]: #class-suitecontext 1829[`TestContext`]: #class-testcontext 1830[`context.diagnostic`]: #contextdiagnosticmessage 1831[`context.skip`]: #contextskipmessage 1832[`context.todo`]: #contexttodomessage 1833[`describe()`]: #describename-options-fn 1834[`run()`]: #runoptions 1835[`test()`]: #testname-options-fn 1836[describe options]: #describename-options-fn 1837[it options]: #testname-options-fn 1838[stream.compose]: stream.md#streamcomposestreams 1839[test reporters]: #test-reporters 1840[test runner execution model]: #test-runner-execution-model 1841