%PDF- %PDF-
Direktori : /usr/share/doc/nodejs/api/ |
Current File : //usr/share/doc/nodejs/api/test.html |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <meta name="nodejs.org:node-version" content="v18.19.1"> <title>Test runner | Node.js v18.19.1 Documentation</title> <link rel="stylesheet" href="assets/style.css"> <link rel="stylesheet" href="assets/hljs.css"> <script async defer src="assets/api.js" type="text/javascript"></script> __JS_FLAVORED_DYNAMIC_CSS__ </head> <body class="alt apidoc" id="api-section-test"> <div id="content" class="clearfix"> <div id="column2" class="interior"> <div id="intro" class="interior"> <a href="index.html" title="Go back to the home page"> Node.js </a> </div> <ul> <li><a href="documentation.html" class="nav-documentation">About this documentation</a></li> <li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li> </ul> <hr class="line"/> <ul> <li><a href="assert.html" class="nav-assert">Assertion testing</a></li> <li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li> <li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li> <li><a href="buffer.html" class="nav-buffer">Buffer</a></li> <li><a href="addons.html" class="nav-addons">C++ addons</a></li> <li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li> <li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li> <li><a href="child_process.html" class="nav-child_process">Child processes</a></li> <li><a href="cluster.html" class="nav-cluster">Cluster</a></li> <li><a href="cli.html" class="nav-cli">Command-line options</a></li> <li><a href="console.html" class="nav-console">Console</a></li> <li><a href="corepack.html" class="nav-corepack">Corepack</a></li> <li><a href="crypto.html" class="nav-crypto">Crypto</a></li> <li><a href="debugger.html" class="nav-debugger">Debugger</a></li> <li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li> <li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li> <li><a href="dns.html" class="nav-dns">DNS</a></li> <li><a href="domain.html" class="nav-domain">Domain</a></li> <li><a href="errors.html" class="nav-errors">Errors</a></li> <li><a href="events.html" class="nav-events">Events</a></li> <li><a href="fs.html" class="nav-fs">File system</a></li> <li><a href="globals.html" class="nav-globals">Globals</a></li> <li><a href="http.html" class="nav-http">HTTP</a></li> <li><a href="http2.html" class="nav-http2">HTTP/2</a></li> <li><a href="https.html" class="nav-https">HTTPS</a></li> <li><a href="inspector.html" class="nav-inspector">Inspector</a></li> <li><a href="intl.html" class="nav-intl">Internationalization</a></li> <li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li> <li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li> <li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li> <li><a href="packages.html" class="nav-packages">Modules: Packages</a></li> <li><a href="net.html" class="nav-net">Net</a></li> <li><a href="os.html" class="nav-os">OS</a></li> <li><a href="path.html" class="nav-path">Path</a></li> <li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li> <li><a href="permissions.html" class="nav-permissions">Permissions</a></li> <li><a href="process.html" class="nav-process">Process</a></li> <li><a href="punycode.html" class="nav-punycode">Punycode</a></li> <li><a href="querystring.html" class="nav-querystring">Query strings</a></li> <li><a href="readline.html" class="nav-readline">Readline</a></li> <li><a href="repl.html" class="nav-repl">REPL</a></li> <li><a href="report.html" class="nav-report">Report</a></li> <li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li> <li><a href="stream.html" class="nav-stream">Stream</a></li> <li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li> <li><a href="test.html" class="nav-test active">Test runner</a></li> <li><a href="timers.html" class="nav-timers">Timers</a></li> <li><a href="tls.html" class="nav-tls">TLS/SSL</a></li> <li><a href="tracing.html" class="nav-tracing">Trace events</a></li> <li><a href="tty.html" class="nav-tty">TTY</a></li> <li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li> <li><a href="url.html" class="nav-url">URL</a></li> <li><a href="util.html" class="nav-util">Utilities</a></li> <li><a href="v8.html" class="nav-v8">V8</a></li> <li><a href="vm.html" class="nav-vm">VM</a></li> <li><a href="wasi.html" class="nav-wasi">WASI</a></li> <li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li> <li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li> <li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li> <li><a href="zlib.html" class="nav-zlib">Zlib</a></li> </ul> <hr class="line"/> <ul> <li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li> </ul> </div> <div id="column1" data-id="test" class="interior"> <header class="header"> <div class="header-container"> <h1>Node.js v18.19.1 documentation</h1> <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden> <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24"> <path fill="none" d="M0 0h24v24H0z" /> <path d="M11.1 12.08c-2.33-4.51-.5-8.48.53-10.07C6.27 2.2 1.98 6.59 1.98 12c0 .14.02.28.02.42.62-.27 1.29-.42 2-.42 1.66 0 3.18.83 4.1 2.15A4.01 4.01 0 0111 18c0 1.52-.87 2.83-2.12 3.51.98.32 2.03.5 3.11.5 3.5 0 6.58-1.8 8.37-4.52-2.36.23-6.98-.97-9.26-5.41z"/> <path d="M7 16h-.18C6.4 14.84 5.3 14 4 14c-1.66 0-3 1.34-3 3s1.34 3 3 3h3c1.1 0 2-.9 2-2s-.9-2-2-2z"/> </svg> <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24"> <path d="M0 0h24v24H0z" fill="none" /> <path d="M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z"/> </svg> </button> </div> <div id="gtoc"> <ul> <li class="pinned-header">Node.js v18.19.1</li> <li class="picker-header"> <a href="#"> <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> Table of contents </a> <div class="picker"><div class="toc"><ul> <li><a href="#test-runner">Test runner</a><ul> <li><a href="#subtests">Subtests</a></li> <li><a href="#skipping-tests">Skipping tests</a></li> <li><a href="#describeit-syntax"><code>describe</code>/<code>it</code> syntax</a></li> <li><a href="#only-tests"><code>only</code> tests</a></li> <li><a href="#filtering-tests-by-name">Filtering tests by name</a></li> <li><a href="#extraneous-asynchronous-activity">Extraneous asynchronous activity</a></li> <li><a href="#watch-mode">Watch mode</a></li> <li><a href="#running-tests-from-the-command-line">Running tests from the command line</a><ul> <li><a href="#test-runner-execution-model">Test runner execution model</a></li> </ul> </li> <li><a href="#collecting-code-coverage">Collecting code coverage</a></li> <li><a href="#mocking">Mocking</a><ul> <li><a href="#timers">Timers</a></li> </ul> </li> <li><a href="#test-reporters">Test reporters</a><ul> <li><a href="#custom-reporters">Custom reporters</a></li> <li><a href="#multiple-reporters">Multiple reporters</a></li> </ul> </li> <li><a href="#runoptions"><code>run([options])</code></a></li> <li><a href="#testname-options-fn"><code>test([name][, options][, fn])</code></a></li> <li><a href="#testskipname-options-fn"><code>test.skip([name][, options][, fn])</code></a></li> <li><a href="#testtodoname-options-fn"><code>test.todo([name][, options][, fn])</code></a></li> <li><a href="#testonlyname-options-fn"><code>test.only([name][, options][, fn])</code></a></li> <li><a href="#describename-options-fn"><code>describe([name][, options][, fn])</code></a></li> <li><a href="#describeskipname-options-fn"><code>describe.skip([name][, options][, fn])</code></a></li> <li><a href="#describetodoname-options-fn"><code>describe.todo([name][, options][, fn])</code></a></li> <li><a href="#describeonlyname-options-fn"><code>describe.only([name][, options][, fn])</code></a></li> <li><a href="#itname-options-fn"><code>it([name][, options][, fn])</code></a></li> <li><a href="#itskipname-options-fn"><code>it.skip([name][, options][, fn])</code></a></li> <li><a href="#ittodoname-options-fn"><code>it.todo([name][, options][, fn])</code></a></li> <li><a href="#itonlyname-options-fn"><code>it.only([name][, options][, fn])</code></a></li> <li><a href="#beforefn-options"><code>before([fn][, options])</code></a></li> <li><a href="#afterfn-options"><code>after([fn][, options])</code></a></li> <li><a href="#beforeeachfn-options"><code>beforeEach([fn][, options])</code></a></li> <li><a href="#aftereachfn-options"><code>afterEach([fn][, options])</code></a></li> <li><a href="#class-mockfunctioncontext">Class: <code>MockFunctionContext</code></a><ul> <li><a href="#ctxcalls"><code>ctx.calls</code></a></li> <li><a href="#ctxcallcount"><code>ctx.callCount()</code></a></li> <li><a href="#ctxmockimplementationimplementation"><code>ctx.mockImplementation(implementation)</code></a></li> <li><a href="#ctxmockimplementationonceimplementation-oncall"><code>ctx.mockImplementationOnce(implementation[, onCall])</code></a></li> <li><a href="#ctxresetcalls"><code>ctx.resetCalls()</code></a></li> <li><a href="#ctxrestore"><code>ctx.restore()</code></a></li> </ul> </li> <li><a href="#class-mocktracker">Class: <code>MockTracker</code></a><ul> <li><a href="#mockfnoriginal-implementation-options"><code>mock.fn([original[, implementation]][, options])</code></a></li> <li><a href="#mockgetterobject-methodname-implementation-options"><code>mock.getter(object, methodName[, implementation][, options])</code></a></li> <li><a href="#mockmethodobject-methodname-implementation-options"><code>mock.method(object, methodName[, implementation][, options])</code></a></li> <li><a href="#mockreset"><code>mock.reset()</code></a></li> <li><a href="#mockrestoreall"><code>mock.restoreAll()</code></a></li> <li><a href="#mocksetterobject-methodname-implementation-options"><code>mock.setter(object, methodName[, implementation][, options])</code></a></li> </ul> </li> <li><a href="#class-mocktimers">Class: <code>MockTimers</code></a><ul> <li><a href="#timersenabletimers"><code>timers.enable([timers])</code></a></li> <li><a href="#timersreset"><code>timers.reset()</code></a></li> <li><a href="#timerssymboldispose"><code>timers[Symbol.dispose]()</code></a></li> <li><a href="#timerstickmilliseconds"><code>timers.tick(milliseconds)</code></a><ul> <li><a href="#using-clear-functions">Using clear functions</a></li> <li><a href="#working-with-nodejs-timers-modules">Working with Node.js timers modules</a></li> </ul> </li> <li><a href="#timersrunall"><code>timers.runAll()</code></a></li> </ul> </li> <li><a href="#class-testsstream">Class: <code>TestsStream</code></a><ul> <li><a href="#event-testcoverage">Event: <code>'test:coverage'</code></a></li> <li><a href="#event-testdequeue">Event: <code>'test:dequeue'</code></a></li> <li><a href="#event-testdiagnostic">Event: <code>'test:diagnostic'</code></a></li> <li><a href="#event-testenqueue">Event: <code>'test:enqueue'</code></a></li> <li><a href="#event-testfail">Event: <code>'test:fail'</code></a></li> <li><a href="#event-testpass">Event: <code>'test:pass'</code></a></li> <li><a href="#event-testplan">Event: <code>'test:plan'</code></a></li> <li><a href="#event-teststart">Event: <code>'test:start'</code></a></li> <li><a href="#event-teststderr">Event: <code>'test:stderr'</code></a></li> <li><a href="#event-teststdout">Event: <code>'test:stdout'</code></a></li> <li><a href="#event-testwatchdrained">Event: <code>'test:watch:drained'</code></a></li> </ul> </li> <li><a href="#class-testcontext">Class: <code>TestContext</code></a><ul> <li><a href="#contextbeforefn-options"><code>context.before([fn][, options])</code></a></li> <li><a href="#contextbeforeeachfn-options"><code>context.beforeEach([fn][, options])</code></a></li> <li><a href="#contextafterfn-options"><code>context.after([fn][, options])</code></a></li> <li><a href="#contextaftereachfn-options"><code>context.afterEach([fn][, options])</code></a></li> <li><a href="#contextdiagnosticmessage"><code>context.diagnostic(message)</code></a></li> <li><a href="#contextname"><code>context.name</code></a></li> <li><a href="#contextrunonlyshouldrunonlytests"><code>context.runOnly(shouldRunOnlyTests)</code></a></li> <li><a href="#contextsignal"><code>context.signal</code></a></li> <li><a href="#contextskipmessage"><code>context.skip([message])</code></a></li> <li><a href="#contexttodomessage"><code>context.todo([message])</code></a></li> <li><a href="#contexttestname-options-fn"><code>context.test([name][, options][, fn])</code></a></li> </ul> </li> <li><a href="#class-suitecontext">Class: <code>SuiteContext</code></a><ul> <li><a href="#contextname_1"><code>context.name</code></a></li> <li><a href="#contextsignal_1"><code>context.signal</code></a></li> </ul> </li> </ul> </li> </ul> </div></div> </li> <li class="picker-header"> <a href="#"> <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> Index </a> <div class="picker"><ul> <li><a href="documentation.html" class="nav-documentation">About this documentation</a></li> <li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li> <li> <a href="index.html">Index</a> </li> </ul> <hr class="line"/> <ul> <li><a href="assert.html" class="nav-assert">Assertion testing</a></li> <li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li> <li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li> <li><a href="buffer.html" class="nav-buffer">Buffer</a></li> <li><a href="addons.html" class="nav-addons">C++ addons</a></li> <li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li> <li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li> <li><a href="child_process.html" class="nav-child_process">Child processes</a></li> <li><a href="cluster.html" class="nav-cluster">Cluster</a></li> <li><a href="cli.html" class="nav-cli">Command-line options</a></li> <li><a href="console.html" class="nav-console">Console</a></li> <li><a href="corepack.html" class="nav-corepack">Corepack</a></li> <li><a href="crypto.html" class="nav-crypto">Crypto</a></li> <li><a href="debugger.html" class="nav-debugger">Debugger</a></li> <li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li> <li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li> <li><a href="dns.html" class="nav-dns">DNS</a></li> <li><a href="domain.html" class="nav-domain">Domain</a></li> <li><a href="errors.html" class="nav-errors">Errors</a></li> <li><a href="events.html" class="nav-events">Events</a></li> <li><a href="fs.html" class="nav-fs">File system</a></li> <li><a href="globals.html" class="nav-globals">Globals</a></li> <li><a href="http.html" class="nav-http">HTTP</a></li> <li><a href="http2.html" class="nav-http2">HTTP/2</a></li> <li><a href="https.html" class="nav-https">HTTPS</a></li> <li><a href="inspector.html" class="nav-inspector">Inspector</a></li> <li><a href="intl.html" class="nav-intl">Internationalization</a></li> <li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li> <li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li> <li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li> <li><a href="packages.html" class="nav-packages">Modules: Packages</a></li> <li><a href="net.html" class="nav-net">Net</a></li> <li><a href="os.html" class="nav-os">OS</a></li> <li><a href="path.html" class="nav-path">Path</a></li> <li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li> <li><a href="permissions.html" class="nav-permissions">Permissions</a></li> <li><a href="process.html" class="nav-process">Process</a></li> <li><a href="punycode.html" class="nav-punycode">Punycode</a></li> <li><a href="querystring.html" class="nav-querystring">Query strings</a></li> <li><a href="readline.html" class="nav-readline">Readline</a></li> <li><a href="repl.html" class="nav-repl">REPL</a></li> <li><a href="report.html" class="nav-report">Report</a></li> <li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li> <li><a href="stream.html" class="nav-stream">Stream</a></li> <li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li> <li><a href="test.html" class="nav-test active">Test runner</a></li> <li><a href="timers.html" class="nav-timers">Timers</a></li> <li><a href="tls.html" class="nav-tls">TLS/SSL</a></li> <li><a href="tracing.html" class="nav-tracing">Trace events</a></li> <li><a href="tty.html" class="nav-tty">TTY</a></li> <li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li> <li><a href="url.html" class="nav-url">URL</a></li> <li><a href="util.html" class="nav-util">Utilities</a></li> <li><a href="v8.html" class="nav-v8">V8</a></li> <li><a href="vm.html" class="nav-vm">VM</a></li> <li><a href="wasi.html" class="nav-wasi">WASI</a></li> <li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li> <li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li> <li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li> <li><a href="zlib.html" class="nav-zlib">Zlib</a></li> </ul> <hr class="line"/> <ul> <li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li> </ul> </div> </li> <li class="picker-header"> <a href="#"> <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> Other versions </a> <div class="picker"><ol id="alt-docs"><li><a href="https://nodejs.org/docs/latest-v18.x/api/test.html">18.x <b>LTS</b></a></li></ol></div> </li> <li class="picker-header"> <a href="#"> <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> Options </a> <div class="picker"> <ul> <li> <a href="all.html">View on single page</a> </li> <li> <a href="test.json">View as JSON</a> </li> <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/master/doc/api/test.md">Edit on GitHub</a></li> </ul> </div> </li> </ul> </div> <hr> </header> <details id="toc" open><summary>Table of contents</summary><ul> <li><a href="#test-runner">Test runner</a><ul> <li><a href="#subtests">Subtests</a></li> <li><a href="#skipping-tests">Skipping tests</a></li> <li><a href="#describeit-syntax"><code>describe</code>/<code>it</code> syntax</a></li> <li><a href="#only-tests"><code>only</code> tests</a></li> <li><a href="#filtering-tests-by-name">Filtering tests by name</a></li> <li><a href="#extraneous-asynchronous-activity">Extraneous asynchronous activity</a></li> <li><a href="#watch-mode">Watch mode</a></li> <li><a href="#running-tests-from-the-command-line">Running tests from the command line</a><ul> <li><a href="#test-runner-execution-model">Test runner execution model</a></li> </ul> </li> <li><a href="#collecting-code-coverage">Collecting code coverage</a></li> <li><a href="#mocking">Mocking</a><ul> <li><a href="#timers">Timers</a></li> </ul> </li> <li><a href="#test-reporters">Test reporters</a><ul> <li><a href="#custom-reporters">Custom reporters</a></li> <li><a href="#multiple-reporters">Multiple reporters</a></li> </ul> </li> <li><a href="#runoptions"><code>run([options])</code></a></li> <li><a href="#testname-options-fn"><code>test([name][, options][, fn])</code></a></li> <li><a href="#testskipname-options-fn"><code>test.skip([name][, options][, fn])</code></a></li> <li><a href="#testtodoname-options-fn"><code>test.todo([name][, options][, fn])</code></a></li> <li><a href="#testonlyname-options-fn"><code>test.only([name][, options][, fn])</code></a></li> <li><a href="#describename-options-fn"><code>describe([name][, options][, fn])</code></a></li> <li><a href="#describeskipname-options-fn"><code>describe.skip([name][, options][, fn])</code></a></li> <li><a href="#describetodoname-options-fn"><code>describe.todo([name][, options][, fn])</code></a></li> <li><a href="#describeonlyname-options-fn"><code>describe.only([name][, options][, fn])</code></a></li> <li><a href="#itname-options-fn"><code>it([name][, options][, fn])</code></a></li> <li><a href="#itskipname-options-fn"><code>it.skip([name][, options][, fn])</code></a></li> <li><a href="#ittodoname-options-fn"><code>it.todo([name][, options][, fn])</code></a></li> <li><a href="#itonlyname-options-fn"><code>it.only([name][, options][, fn])</code></a></li> <li><a href="#beforefn-options"><code>before([fn][, options])</code></a></li> <li><a href="#afterfn-options"><code>after([fn][, options])</code></a></li> <li><a href="#beforeeachfn-options"><code>beforeEach([fn][, options])</code></a></li> <li><a href="#aftereachfn-options"><code>afterEach([fn][, options])</code></a></li> <li><a href="#class-mockfunctioncontext">Class: <code>MockFunctionContext</code></a><ul> <li><a href="#ctxcalls"><code>ctx.calls</code></a></li> <li><a href="#ctxcallcount"><code>ctx.callCount()</code></a></li> <li><a href="#ctxmockimplementationimplementation"><code>ctx.mockImplementation(implementation)</code></a></li> <li><a href="#ctxmockimplementationonceimplementation-oncall"><code>ctx.mockImplementationOnce(implementation[, onCall])</code></a></li> <li><a href="#ctxresetcalls"><code>ctx.resetCalls()</code></a></li> <li><a href="#ctxrestore"><code>ctx.restore()</code></a></li> </ul> </li> <li><a href="#class-mocktracker">Class: <code>MockTracker</code></a><ul> <li><a href="#mockfnoriginal-implementation-options"><code>mock.fn([original[, implementation]][, options])</code></a></li> <li><a href="#mockgetterobject-methodname-implementation-options"><code>mock.getter(object, methodName[, implementation][, options])</code></a></li> <li><a href="#mockmethodobject-methodname-implementation-options"><code>mock.method(object, methodName[, implementation][, options])</code></a></li> <li><a href="#mockreset"><code>mock.reset()</code></a></li> <li><a href="#mockrestoreall"><code>mock.restoreAll()</code></a></li> <li><a href="#mocksetterobject-methodname-implementation-options"><code>mock.setter(object, methodName[, implementation][, options])</code></a></li> </ul> </li> <li><a href="#class-mocktimers">Class: <code>MockTimers</code></a><ul> <li><a href="#timersenabletimers"><code>timers.enable([timers])</code></a></li> <li><a href="#timersreset"><code>timers.reset()</code></a></li> <li><a href="#timerssymboldispose"><code>timers[Symbol.dispose]()</code></a></li> <li><a href="#timerstickmilliseconds"><code>timers.tick(milliseconds)</code></a><ul> <li><a href="#using-clear-functions">Using clear functions</a></li> <li><a href="#working-with-nodejs-timers-modules">Working with Node.js timers modules</a></li> </ul> </li> <li><a href="#timersrunall"><code>timers.runAll()</code></a></li> </ul> </li> <li><a href="#class-testsstream">Class: <code>TestsStream</code></a><ul> <li><a href="#event-testcoverage">Event: <code>'test:coverage'</code></a></li> <li><a href="#event-testdequeue">Event: <code>'test:dequeue'</code></a></li> <li><a href="#event-testdiagnostic">Event: <code>'test:diagnostic'</code></a></li> <li><a href="#event-testenqueue">Event: <code>'test:enqueue'</code></a></li> <li><a href="#event-testfail">Event: <code>'test:fail'</code></a></li> <li><a href="#event-testpass">Event: <code>'test:pass'</code></a></li> <li><a href="#event-testplan">Event: <code>'test:plan'</code></a></li> <li><a href="#event-teststart">Event: <code>'test:start'</code></a></li> <li><a href="#event-teststderr">Event: <code>'test:stderr'</code></a></li> <li><a href="#event-teststdout">Event: <code>'test:stdout'</code></a></li> <li><a href="#event-testwatchdrained">Event: <code>'test:watch:drained'</code></a></li> </ul> </li> <li><a href="#class-testcontext">Class: <code>TestContext</code></a><ul> <li><a href="#contextbeforefn-options"><code>context.before([fn][, options])</code></a></li> <li><a href="#contextbeforeeachfn-options"><code>context.beforeEach([fn][, options])</code></a></li> <li><a href="#contextafterfn-options"><code>context.after([fn][, options])</code></a></li> <li><a href="#contextaftereachfn-options"><code>context.afterEach([fn][, options])</code></a></li> <li><a href="#contextdiagnosticmessage"><code>context.diagnostic(message)</code></a></li> <li><a href="#contextname"><code>context.name</code></a></li> <li><a href="#contextrunonlyshouldrunonlytests"><code>context.runOnly(shouldRunOnlyTests)</code></a></li> <li><a href="#contextsignal"><code>context.signal</code></a></li> <li><a href="#contextskipmessage"><code>context.skip([message])</code></a></li> <li><a href="#contexttodomessage"><code>context.todo([message])</code></a></li> <li><a href="#contexttestname-options-fn"><code>context.test([name][, options][, fn])</code></a></li> </ul> </li> <li><a href="#class-suitecontext">Class: <code>SuiteContext</code></a><ul> <li><a href="#contextname_1"><code>context.name</code></a></li> <li><a href="#contextsignal_1"><code>context.signal</code></a></li> </ul> </li> </ul> </li> </ul> </details> <div id="apicontent"> <h2>Test runner<span><a class="mark" href="#test-runner" id="test-runner">#</a></span><a aria-hidden="true" class="legacy" id="test_test_runner"></a></h2> <!--introduced_in=v18.0.0--> <div class="api_metadata"> <span>Added in: v18.0.0, v16.17.0</span> </div><blockquote> <p>Stability: 1 - Experimental</p> </blockquote> <!-- source_link=lib/test.js --> <p>The <code>node:test</code> module facilitates the creation of JavaScript tests. To access it:</p> <pre><code class="language-mjs">import test from 'node:test'; </code></pre> <pre><code class="language-cjs">const test = require('node:test'); </code></pre> <p>This module is only available under the <code>node:</code> scheme. The following will not work:</p> <pre><code class="language-mjs">import test from 'test'; </code></pre> <pre><code class="language-cjs">const test = require('test'); </code></pre> <p>Tests created via the <code>test</code> module consist of a single function that is processed in one of three ways:</p> <ol> <li>A synchronous function that is considered failing if it throws an exception, and is considered passing otherwise.</li> <li>A function that returns a <code>Promise</code> that is considered failing if the <code>Promise</code> rejects, and is considered passing if the <code>Promise</code> resolves.</li> <li>A function that receives a callback function. If the callback receives any truthy value as its first argument, the test is considered failing. If a falsy value is passed as the first argument to the callback, the test is considered passing. If the test function receives a callback function and also returns a <code>Promise</code>, the test will fail.</li> </ol> <p>The following example illustrates how tests are written using the <code>test</code> module.</p> <pre><code class="language-js">test('synchronous passing test', (t) => { // This test passes because it does not throw an exception. assert.strictEqual(1, 1); }); test('synchronous failing test', (t) => { // This test fails because it throws an exception. assert.strictEqual(1, 2); }); test('asynchronous passing test', async (t) => { // This test passes because the Promise returned by the async // function is not rejected. assert.strictEqual(1, 1); }); test('asynchronous failing test', async (t) => { // This test fails because the Promise returned by the async // function is rejected. assert.strictEqual(1, 2); }); test('failing test using Promises', (t) => { // Promises can be used directly as well. return new Promise((resolve, reject) => { setImmediate(() => { reject(new Error('this will cause the test to fail')); }); }); }); test('callback passing test', (t, done) => { // done() is the callback function. When the setImmediate() runs, it invokes // done() with no arguments. setImmediate(done); }); test('callback failing test', (t, done) => { // When the setImmediate() runs, done() is invoked with an Error object and // the test fails. setImmediate(() => { done(new Error('callback failure')); }); }); </code></pre> <p>If any tests fail, the process exit code is set to <code>1</code>.</p> <section><h3>Subtests<span><a class="mark" href="#subtests" id="subtests">#</a></span><a aria-hidden="true" class="legacy" id="test_subtests"></a></h3> <p>The test context's <code>test()</code> method allows subtests to be created. This method behaves identically to the top level <code>test()</code> function. The following example demonstrates the creation of a top level test with two subtests.</p> <pre><code class="language-js">test('top level test', async (t) => { await t.test('subtest 1', (t) => { assert.strictEqual(1, 1); }); await t.test('subtest 2', (t) => { assert.strictEqual(2, 2); }); }); </code></pre> <p>In this example, <code>await</code> is used to ensure that both subtests have completed. This is necessary because parent tests do not wait for their subtests to complete. Any subtests that are still outstanding when their parent finishes are cancelled and treated as failures. Any subtest failures cause the parent test to fail.</p> </section><section><h3>Skipping tests<span><a class="mark" href="#skipping-tests" id="skipping-tests">#</a></span><a aria-hidden="true" class="legacy" id="test_skipping_tests"></a></h3> <p>Individual tests can be skipped by passing the <code>skip</code> option to the test, or by calling the test context's <code>skip()</code> method as shown in the following example.</p> <pre><code class="language-js">// The skip option is used, but no message is provided. test('skip option', { skip: true }, (t) => { // This code is never executed. }); // The skip option is used, and a message is provided. test('skip option with message', { skip: 'this is skipped' }, (t) => { // This code is never executed. }); test('skip() method', (t) => { // Make sure to return here as well if the test contains additional logic. t.skip(); }); test('skip() method with message', (t) => { // Make sure to return here as well if the test contains additional logic. t.skip('this is skipped'); }); </code></pre> </section><section><h3><code>describe</code>/<code>it</code> syntax<span><a class="mark" href="#describeit-syntax" id="describeit-syntax">#</a></span><a aria-hidden="true" class="legacy" id="test_describe_it_syntax"></a></h3> <p>Running tests can also be done using <code>describe</code> to declare a suite and <code>it</code> to declare a test. A suite is used to organize and group related tests together. <code>it</code> is a shorthand for <a href="#testname-options-fn"><code>test()</code></a>.</p> <pre><code class="language-js">describe('A thing', () => { it('should work', () => { assert.strictEqual(1, 1); }); it('should be ok', () => { assert.strictEqual(2, 2); }); describe('a nested thing', () => { it('should work', () => { assert.strictEqual(3, 3); }); }); }); </code></pre> <p><code>describe</code> and <code>it</code> are imported from the <code>node:test</code> module.</p> <pre><code class="language-mjs">import { describe, it } from 'node:test'; </code></pre> <pre><code class="language-cjs">const { describe, it } = require('node:test'); </code></pre> </section><section><h3><code>only</code> tests<span><a class="mark" href="#only-tests" id="only-tests">#</a></span><a aria-hidden="true" class="legacy" id="test_only_tests"></a></h3> <p>If Node.js is started with the <a href="cli.html#--test-only"><code>--test-only</code></a> command-line option, it is possible to skip all top level tests except for a selected subset by passing the <code>only</code> option to the tests that should be run. When a test with the <code>only</code> option set is run, all subtests are also run. The test context's <code>runOnly()</code> method can be used to implement the same behavior at the subtest level.</p> <pre><code class="language-js">// Assume Node.js is run with the --test-only command-line option. // The 'only' option is set, so this test is run. test('this test is run', { only: true }, async (t) => { // Within this test, all subtests are run by default. await t.test('running subtest'); // The test context can be updated to run subtests with the 'only' option. t.runOnly(true); await t.test('this subtest is now skipped'); await t.test('this subtest is run', { only: true }); // Switch the context back to execute all tests. t.runOnly(false); await t.test('this subtest is now run'); // Explicitly do not run these tests. await t.test('skipped subtest 3', { only: false }); await t.test('skipped subtest 4', { skip: true }); }); // The 'only' option is not set, so this test is skipped. test('this test is not run', () => { // This code is not run. throw new Error('fail'); }); </code></pre> </section><section><h3>Filtering tests by name<span><a class="mark" href="#filtering-tests-by-name" id="filtering-tests-by-name">#</a></span><a aria-hidden="true" class="legacy" id="test_filtering_tests_by_name"></a></h3> <p>The <a href="cli.html#--test-name-pattern"><code>--test-name-pattern</code></a> command-line option can be used to only run tests whose name matches the provided pattern. Test name patterns are interpreted as JavaScript regular expressions. The <code>--test-name-pattern</code> option can be specified multiple times in order to run nested tests. For each test that is executed, any corresponding test hooks, such as <code>beforeEach()</code>, are also run.</p> <p>Given the following test file, starting Node.js with the <code>--test-name-pattern="test [1-3]"</code> option would cause the test runner to execute <code>test 1</code>, <code>test 2</code>, and <code>test 3</code>. If <code>test 1</code> did not match the test name pattern, then its subtests would not execute, despite matching the pattern. The same set of tests could also be executed by passing <code>--test-name-pattern</code> multiple times (e.g. <code>--test-name-pattern="test 1"</code>, <code>--test-name-pattern="test 2"</code>, etc.).</p> <pre><code class="language-js">test('test 1', async (t) => { await t.test('test 2'); await t.test('test 3'); }); test('Test 4', async (t) => { await t.test('Test 5'); await t.test('test 6'); }); </code></pre> <p>Test name patterns can also be specified using regular expression literals. This allows regular expression flags to be used. In the previous example, starting Node.js with <code>--test-name-pattern="/test [4-5]/i"</code> would match <code>Test 4</code> and <code>Test 5</code> because the pattern is case-insensitive.</p> <p>Test name patterns do not change the set of files that the test runner executes.</p> </section><section><h3>Extraneous asynchronous activity<span><a class="mark" href="#extraneous-asynchronous-activity" id="extraneous-asynchronous-activity">#</a></span><a aria-hidden="true" class="legacy" id="test_extraneous_asynchronous_activity"></a></h3> <p>Once a test function finishes executing, the results are reported as quickly as possible while maintaining the order of the tests. However, it is possible for the test function to generate asynchronous activity that outlives the test itself. The test runner handles this type of activity, but does not delay the reporting of test results in order to accommodate it.</p> <p>In the following example, a test completes with two <code>setImmediate()</code> operations still outstanding. The first <code>setImmediate()</code> attempts to create a new subtest. Because the parent test has already finished and output its results, the new subtest is immediately marked as failed, and reported later to the <a href="test.html#class-testsstream" class="type"><TestsStream></a>.</p> <p>The second <code>setImmediate()</code> creates an <code>uncaughtException</code> event. <code>uncaughtException</code> and <code>unhandledRejection</code> events originating from a completed test are marked as failed by the <code>test</code> module and reported as diagnostic warnings at the top level by the <a href="test.html#class-testsstream" class="type"><TestsStream></a>.</p> <pre><code class="language-js">test('a test that creates asynchronous activity', (t) => { setImmediate(() => { t.test('subtest that is created too late', (t) => { throw new Error('error1'); }); }); setImmediate(() => { throw new Error('error2'); }); // The test finishes after this line. }); </code></pre> </section><section><h3>Watch mode<span><a class="mark" href="#watch-mode" id="watch-mode">#</a></span><a aria-hidden="true" class="legacy" id="test_watch_mode"></a></h3> <div class="api_metadata"> <span>Added in: v18.13.0</span> </div><blockquote> <p>Stability: 1 - Experimental</p> </blockquote> <p>The Node.js test runner supports running in watch mode by passing the <code>--watch</code> flag:</p> <pre><code class="language-bash">node --test --watch </code></pre> <p>In watch mode, the test runner will watch for changes to test files and their dependencies. When a change is detected, the test runner will rerun the tests affected by the change. The test runner will continue to run until the process is terminated.</p> </section><section><h3>Running tests from the command line<span><a class="mark" href="#running-tests-from-the-command-line" id="running-tests-from-the-command-line">#</a></span><a aria-hidden="true" class="legacy" id="test_running_tests_from_the_command_line"></a></h3> <p>The Node.js test runner can be invoked from the command line by passing the <a href="cli.html#--test"><code>--test</code></a> flag:</p> <pre><code class="language-bash">node --test </code></pre> <p>By default, Node.js will recursively search the current directory for JavaScript source files matching a specific naming convention. Matching files are executed as test files. More information on the expected test file naming convention and behavior can be found in the <a href="#test-runner-execution-model">test runner execution model</a> section.</p> <p>Alternatively, one or more paths can be provided as the final argument(s) to the Node.js command, as shown below.</p> <pre><code class="language-bash">node --test test1.js test2.mjs custom_test_dir/ </code></pre> <p>In this example, the test runner will execute the files <code>test1.js</code> and <code>test2.mjs</code>. The test runner will also recursively search the <code>custom_test_dir/</code> directory for test files to execute.</p> <h4>Test runner execution model<span><a class="mark" href="#test-runner-execution-model" id="test-runner-execution-model">#</a></span><a aria-hidden="true" class="legacy" id="test_test_runner_execution_model"></a></h4> <p>When searching for test files to execute, the test runner behaves as follows:</p> <ul> <li>Any files explicitly provided by the user are executed.</li> <li>If the user did not explicitly specify any paths, the current working directory is recursively searched for files as specified in the following steps.</li> <li><code>node_modules</code> directories are skipped unless explicitly provided by the user.</li> <li>If a directory named <code>test</code> is encountered, the test runner will search it recursively for all all <code>.js</code>, <code>.cjs</code>, and <code>.mjs</code> files. All of these files are treated as test files, and do not need to match the specific naming convention detailed below. This is to accommodate projects that place all of their tests in a single <code>test</code> directory.</li> <li>In all other directories, <code>.js</code>, <code>.cjs</code>, and <code>.mjs</code> files matching the following patterns are treated as test files:<ul> <li><code>^test$</code> - Files whose basename is the string <code>'test'</code>. Examples: <code>test.js</code>, <code>test.cjs</code>, <code>test.mjs</code>.</li> <li><code>^test-.+</code> - Files whose basename starts with the string <code>'test-'</code> followed by one or more characters. Examples: <code>test-example.js</code>, <code>test-another-example.mjs</code>.</li> <li><code>.+[\.\-\_]test$</code> - Files whose basename ends with <code>.test</code>, <code>-test</code>, or <code>_test</code>, preceded by one or more characters. Examples: <code>example.test.js</code>, <code>example-test.cjs</code>, <code>example_test.mjs</code>.</li> <li>Other file types understood by Node.js such as <code>.node</code> and <code>.json</code> are not automatically executed by the test runner, but are supported if explicitly provided on the command line.</li> </ul> </li> </ul> <p>Each matching test file is executed in a separate child process. The maximum number of child processes running at any time is controlled by the <a href="cli.html#--test-concurrency"><code>--test-concurrency</code></a> flag. If the child process finishes with an exit code of 0, the test is considered passing. Otherwise, the test is considered to be a failure. Test files must be executable by Node.js, but are not required to use the <code>node:test</code> module internally.</p> <p>Each test file is executed as if it was a regular script. That is, if the test file itself uses <code>node:test</code> to define tests, all of those tests will be executed within a single application thread, regardless of the value of the <code>concurrency</code> option of <a href="#testname-options-fn"><code>test()</code></a>.</p> </section><section><h3>Collecting code coverage<span><a class="mark" href="#collecting-code-coverage" id="collecting-code-coverage">#</a></span><a aria-hidden="true" class="legacy" id="test_collecting_code_coverage"></a></h3> <p>When Node.js is started with the <a href="cli.html#--experimental-test-coverage"><code>--experimental-test-coverage</code></a> command-line flag, code coverage is collected and statistics are reported once all tests have completed. If the <a href="cli.html#node_v8_coveragedir"><code>NODE_V8_COVERAGE</code></a> environment variable is used to specify a code coverage directory, the generated V8 coverage files are written to that directory. Node.js core modules and files within <code>node_modules/</code> directories are not included in the coverage report. If coverage is enabled, the coverage report is sent to any <a href="#test-reporters">test reporters</a> via the <code>'test:coverage'</code> event.</p> <p>Coverage can be disabled on a series of lines using the following comment syntax:</p> <pre><code class="language-js">/* node:coverage disable */ if (anAlwaysFalseCondition) { // Code in this branch will never be executed, but the lines are ignored for // coverage purposes. All lines following the 'disable' comment are ignored // until a corresponding 'enable' comment is encountered. console.log('this is never executed'); } /* node:coverage enable */ </code></pre> <p>Coverage can also be disabled for a specified number of lines. After the specified number of lines, coverage will be automatically reenabled. If the number of lines is not explicitly provided, a single line is ignored.</p> <pre><code class="language-js">/* node:coverage ignore next */ if (anAlwaysFalseCondition) { console.log('this is never executed'); } /* node:coverage ignore next 3 */ if (anAlwaysFalseCondition) { console.log('this is never executed'); } </code></pre> <p>The test runner's code coverage functionality has the following limitations, which will be addressed in a future Node.js release:</p> <ul> <li>Source maps are not supported.</li> <li>Excluding specific files or directories from the coverage report is not supported.</li> </ul> </section><section><h3>Mocking<span><a class="mark" href="#mocking" id="mocking">#</a></span><a aria-hidden="true" class="legacy" id="test_mocking"></a></h3> <p>The <code>node:test</code> module supports mocking during testing via a top-level <code>mock</code> object. The following example creates a spy on a function that adds two numbers together. The spy is then used to assert that the function was called as expected.</p> <pre><code class="language-mjs">import assert from 'node:assert'; import { mock, test } from 'node:test'; test('spies on a function', () => { const sum = mock.fn((a, b) => { return a + b; }); assert.strictEqual(sum.mock.calls.length, 0); assert.strictEqual(sum(3, 4), 7); assert.strictEqual(sum.mock.calls.length, 1); const call = sum.mock.calls[0]; assert.deepStrictEqual(call.arguments, [3, 4]); assert.strictEqual(call.result, 7); assert.strictEqual(call.error, undefined); // Reset the globally tracked mocks. mock.reset(); }); </code></pre> <pre><code class="language-cjs">'use strict'; const assert = require('node:assert'); const { mock, test } = require('node:test'); test('spies on a function', () => { const sum = mock.fn((a, b) => { return a + b; }); assert.strictEqual(sum.mock.calls.length, 0); assert.strictEqual(sum(3, 4), 7); assert.strictEqual(sum.mock.calls.length, 1); const call = sum.mock.calls[0]; assert.deepStrictEqual(call.arguments, [3, 4]); assert.strictEqual(call.result, 7); assert.strictEqual(call.error, undefined); // Reset the globally tracked mocks. mock.reset(); }); </code></pre> <p>The same mocking functionality is also exposed on the <a href="#class-testcontext"><code>TestContext</code></a> object of each test. The following example creates a spy on an object method using the API exposed on the <code>TestContext</code>. The benefit of mocking via the test context is that the test runner will automatically restore all mocked functionality once the test finishes.</p> <pre><code class="language-js">test('spies on an object method', (t) => { const number = { value: 5, add(a) { return this.value + a; }, }; t.mock.method(number, 'add'); assert.strictEqual(number.add.mock.calls.length, 0); assert.strictEqual(number.add(3), 8); assert.strictEqual(number.add.mock.calls.length, 1); const call = number.add.mock.calls[0]; assert.deepStrictEqual(call.arguments, [3]); assert.strictEqual(call.result, 8); assert.strictEqual(call.target, undefined); assert.strictEqual(call.this, number); }); </code></pre> <h4>Timers<span><a class="mark" href="#timers" id="timers">#</a></span><a aria-hidden="true" class="legacy" id="test_timers"></a></h4> <p>Mocking timers is a technique commonly used in software testing to simulate and control the behavior of timers, such as <code>setInterval</code> and <code>setTimeout</code>, without actually waiting for the specified time intervals.</p> <p>Refer to the <a href="#class-mocktimers"><code>MockTimers</code></a> class for a full list of methods and features.</p> <p>This allows developers to write more reliable and predictable tests for time-dependent functionality.</p> <p>The example below shows how to mock <code>setTimeout</code>. Using <code>.enable(['setTimeout']);</code> it will mock the <code>setTimeout</code> functions in the <a href="./timers.html">node:timers</a> and <a href="./timers.html#timers-promises-api">node:timers/promises</a> modules, as well as from the Node.js global context.</p> <p><strong>Note:</strong> Destructuring functions such as <code>import { setTimeout } from 'node:timers'</code> is currently not supported by this API.</p> <pre><code class="language-mjs">import assert from 'node:assert'; import { mock, test } from 'node:test'; test('mocks setTimeout to be executed synchronously without having to actually wait for it', () => { const fn = mock.fn(); // Optionally choose what to mock mock.timers.enable(['setTimeout']); setTimeout(fn, 9999); assert.strictEqual(fn.mock.callCount(), 0); // Advance in time mock.timers.tick(9999); assert.strictEqual(fn.mock.callCount(), 1); // Reset the globally tracked mocks. mock.timers.reset(); // If you call reset mock instance, it will also reset timers instance mock.reset(); }); </code></pre> <pre><code class="language-js">const assert = require('node:assert'); const { mock, test } = require('node:test'); test('mocks setTimeout to be executed synchronously without having to actually wait for it', () => { const fn = mock.fn(); // Optionally choose what to mock mock.timers.enable(['setTimeout']); setTimeout(fn, 9999); assert.strictEqual(fn.mock.callCount(), 0); // Advance in time mock.timers.tick(9999); assert.strictEqual(fn.mock.callCount(), 1); // Reset the globally tracked mocks. mock.timers.reset(); // If you call reset mock instance, it'll also reset timers instance mock.reset(); }); </code></pre> <p>The same mocking functionality is also exposed in the mock property on the <a href="#class-testcontext"><code>TestContext</code></a> object of each test. The benefit of mocking via the test context is that the test runner will automatically restore all mocked timers functionality once the test finishes.</p> <pre><code class="language-mjs">import assert from 'node:assert'; import { test } from 'node:test'; test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { const fn = context.mock.fn(); // Optionally choose what to mock context.mock.timers.enable(['setTimeout']); setTimeout(fn, 9999); assert.strictEqual(fn.mock.callCount(), 0); // Advance in time context.mock.timers.tick(9999); assert.strictEqual(fn.mock.callCount(), 1); }); </code></pre> <pre><code class="language-js">const assert = require('node:assert'); const { test } = require('node:test'); test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { const fn = context.mock.fn(); // Optionally choose what to mock context.mock.timers.enable(['setTimeout']); setTimeout(fn, 9999); assert.strictEqual(fn.mock.callCount(), 0); // Advance in time context.mock.timers.tick(9999); assert.strictEqual(fn.mock.callCount(), 1); }); </code></pre> </section><section><h3>Test reporters<span><a class="mark" href="#test-reporters" id="test-reporters">#</a></span><a aria-hidden="true" class="legacy" id="test_test_reporters"></a></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v18.17.0</td> <td><p>Reporters are now exposed at <code>node:test/reporters</code>.</p> </td></tr> <tr><td>v18.15.0</td> <td><p><span>Added in: v18.15.0</span></p> </td></tr> </table> </details> </div><p>The <code>node:test</code> module supports passing <a href="cli.html#--test-reporter"><code>--test-reporter</code></a> flags for the test runner to use a specific reporter.</p> <p>The following built-reporters are supported:</p> <ul> <li><p><code>tap</code> The <code>tap</code> reporter outputs the test results in the <a href="https://testanything.org/">TAP</a> format.</p> </li> <li><p><code>spec</code> The <code>spec</code> reporter outputs the test results in a human-readable format.</p> </li> <li><p><code>dot</code> The <code>dot</code> reporter outputs the test results in a compact format, where each passing test is represented by a <code>.</code>, and each failing test is represented by a <code>X</code>.</p> </li> <li><p><code>junit</code> The junit reporter outputs test results in a jUnit XML format</p> </li> </ul> <p>When <code>stdout</code> is a <a href="tty.html">TTY</a>, the <code>spec</code> reporter is used by default. Otherwise, the <code>tap</code> reporter is used by default.</p> <p>The reporters are available via the <code>node:test/reporters</code> module:</p> <pre><code class="language-mjs">import { tap, spec, dot, junit } from 'node:test/reporters'; </code></pre> <pre><code class="language-cjs">const { tap, spec, dot, junit } = require('node:test/reporters'); </code></pre> <h4>Custom reporters<span><a class="mark" href="#custom-reporters" id="custom-reporters">#</a></span><a aria-hidden="true" class="legacy" id="test_custom_reporters"></a></h4> <p><a href="cli.html#--test-reporter"><code>--test-reporter</code></a> can be used to specify a path to custom reporter. A custom reporter is a module that exports a value accepted by <a href="stream.html#streamcomposestreams">stream.compose</a>. Reporters should transform events emitted by a <a href="test.html#class-testsstream" class="type"><TestsStream></a></p> <p>Example of a custom reporter using {stream.Transform}:</p> <pre><code class="language-mjs">import { Transform } from 'node:stream'; const customReporter = new Transform({ writableObjectMode: true, transform(event, encoding, callback) { switch (event.type) { case 'test:dequeue': callback(null, `test ${event.data.name} dequeued`); break; case 'test:enqueue': callback(null, `test ${event.data.name} enqueued`); break; case 'test:watch:drained': callback(null, 'test watch queue drained'); break; case 'test:start': callback(null, `test ${event.data.name} started`); break; case 'test:pass': callback(null, `test ${event.data.name} passed`); break; case 'test:fail': callback(null, `test ${event.data.name} failed`); break; case 'test:plan': callback(null, 'test plan'); break; case 'test:diagnostic': case 'test:stderr': case 'test:stdout': callback(null, event.data.message); break; case 'test:coverage': { const { totalLineCount } = event.data.summary.totals; callback(null, `total line count: ${totalLineCount}\n`); break; } } }, }); export default customReporter; </code></pre> <pre><code class="language-cjs">const { Transform } = require('node:stream'); const customReporter = new Transform({ writableObjectMode: true, transform(event, encoding, callback) { switch (event.type) { case 'test:dequeue': callback(null, `test ${event.data.name} dequeued`); break; case 'test:enqueue': callback(null, `test ${event.data.name} enqueued`); break; case 'test:watch:drained': callback(null, 'test watch queue drained'); break; case 'test:start': callback(null, `test ${event.data.name} started`); break; case 'test:pass': callback(null, `test ${event.data.name} passed`); break; case 'test:fail': callback(null, `test ${event.data.name} failed`); break; case 'test:plan': callback(null, 'test plan'); break; case 'test:diagnostic': case 'test:stderr': case 'test:stdout': callback(null, event.data.message); break; case 'test:coverage': { const { totalLineCount } = event.data.summary.totals; callback(null, `total line count: ${totalLineCount}\n`); break; } } }, }); module.exports = customReporter; </code></pre> <p>Example of a custom reporter using a generator function:</p> <pre><code class="language-mjs">export default async function * customReporter(source) { for await (const event of source) { switch (event.type) { case 'test:dequeue': yield `test ${event.data.name} dequeued`; break; case 'test:enqueue': yield `test ${event.data.name} enqueued`; break; case 'test:watch:drained': yield 'test watch queue drained'; break; case 'test:start': yield `test ${event.data.name} started\n`; break; case 'test:pass': yield `test ${event.data.name} passed\n`; break; case 'test:fail': yield `test ${event.data.name} failed\n`; break; case 'test:plan': yield 'test plan'; break; case 'test:diagnostic': case 'test:stderr': case 'test:stdout': yield `${event.data.message}\n`; break; case 'test:coverage': { const { totalLineCount } = event.data.summary.totals; yield `total line count: ${totalLineCount}\n`; break; } } } } </code></pre> <pre><code class="language-cjs">module.exports = async function * customReporter(source) { for await (const event of source) { switch (event.type) { case 'test:dequeue': yield `test ${event.data.name} dequeued`; break; case 'test:enqueue': yield `test ${event.data.name} enqueued`; break; case 'test:watch:drained': yield 'test watch queue drained'; break; case 'test:start': yield `test ${event.data.name} started\n`; break; case 'test:pass': yield `test ${event.data.name} passed\n`; break; case 'test:fail': yield `test ${event.data.name} failed\n`; break; case 'test:plan': yield 'test plan\n'; break; case 'test:diagnostic': case 'test:stderr': case 'test:stdout': yield `${event.data.message}\n`; break; case 'test:coverage': { const { totalLineCount } = event.data.summary.totals; yield `total line count: ${totalLineCount}\n`; break; } } } }; </code></pre> <p>The value provided to <code>--test-reporter</code> should be a string like one used in an <code>import()</code> in JavaScript code.</p> <h4>Multiple reporters<span><a class="mark" href="#multiple-reporters" id="multiple-reporters">#</a></span><a aria-hidden="true" class="legacy" id="test_multiple_reporters"></a></h4> <p>The <a href="cli.html#--test-reporter"><code>--test-reporter</code></a> flag can be specified multiple times to report test results in several formats. In this situation it is required to specify a destination for each reporter using <a href="cli.html#--test-reporter-destination"><code>--test-reporter-destination</code></a>. Destination can be <code>stdout</code>, <code>stderr</code>, or a file path. Reporters and destinations are paired according to the order they were specified.</p> <p>In the following example, the <code>spec</code> reporter will output to <code>stdout</code>, and the <code>dot</code> reporter will output to <code>file.txt</code>:</p> <pre><code class="language-bash">node --test-reporter=spec --test-reporter=dot --test-reporter-destination=stdout --test-reporter-destination=file.txt </code></pre> <p>When a single reporter is specified, the destination will default to <code>stdout</code>, unless a destination is explicitly provided.</p> </section><section><h3><code>run([options])</code><span><a class="mark" href="#runoptions" id="runoptions">#</a></span><a aria-hidden="true" class="legacy" id="test_run_options"></a></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v18.17.0</td> <td><p>Add a testNamePatterns option.</p> </td></tr> <tr><td>v18.9.0</td> <td><p><span>Added in: v18.9.0</span></p> </td></tr> </table> </details> </div><ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Configuration options for running tests. The following properties are supported:<ul> <li><code>concurrency</code> {number|boolean} If a number is provided, then that many test processes would run in parallel, where each process corresponds to one test file. If <code>true</code>, it would run <code>os.availableParallelism() - 1</code> test files in parallel. If <code>false</code>, it would only run one test file at a time. <strong>Default:</strong> <code>false</code>.</li> <li><code>files</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> An array containing the list of files to run. <strong>Default</strong> matching files from <a href="#test-runner-execution-model">test runner execution model</a>.</li> <li><code>inspectPort</code> {number|Function} Sets inspector port of test child process. This can be a number, or a function that takes no arguments and returns a number. If a nullish value is provided, each process gets its own port, incremented from the primary's <code>process.debugPort</code>. <strong>Default:</strong> <code>undefined</code>.</li> <li><code>only</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If truthy, the test context will only run tests that have the <code>only</code> option set</li> <li><code>setup</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A function that accepts the <code>TestsStream</code> instance and can be used to setup listeners before any tests are run. <strong>Default:</strong> <code>undefined</code>.</li> <li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> Allows aborting an in-progress test execution.</li> <li><code>testNamePatterns</code> {string|RegExp|Array} A String, RegExp or a RegExp Array, that can be used to only run tests whose name matches the provided pattern. Test name patterns are interpreted as JavaScript regular expressions. For each test that is executed, any corresponding test hooks, such as <code>beforeEach()</code>, are also run. <strong>Default:</strong> <code>undefined</code>.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A number of milliseconds the test execution will fail after. If unspecified, subtests inherit this value from their parent. <strong>Default:</strong> <code>Infinity</code>.</li> <li><code>watch</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether to run in watch mode or not. <strong>Default:</strong> <code>false</code>.</li> <li><code>shard</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Running tests in a specific shard. <strong>Default:</strong> <code>undefined</code>.<ul> <li><code>index</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> is a positive integer between 1 and <code><total></code> that specifies the index of the shard to run. This option is <em>required</em>.</li> <li><code>total</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> is a positive integer that specifies the total number of shards to split the test files to. This option is <em>required</em>.</li> </ul> </li> </ul> </li> <li>Returns: <a href="test.html#class-testsstream" class="type"><TestsStream></a></li> </ul> <pre><code class="language-mjs">import { tap } from 'node:test/reporters'; import process from 'node:process'; run({ files: [path.resolve('./tests/test.js')] }) .compose(tap) .pipe(process.stdout); </code></pre> <pre><code class="language-cjs">const { tap } = require('node:test/reporters'); run({ files: [path.resolve('./tests/test.js')] }) .compose(tap) .pipe(process.stdout); </code></pre> </section><section><h3><code>test([name][, options][, fn])</code><span><a class="mark" href="#testname-options-fn" id="testname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_test_name_options_fn"></a></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v18.17.0</td> <td><p>Added the <code>skip</code>, <code>todo</code>, and <code>only</code> shorthands.</p> </td></tr> <tr><td>v18.8.0</td> <td><p>Add a <code>signal</code> option.</p> </td></tr> <tr><td>v18.7.0</td> <td><p>Add a <code>timeout</code> option.</p> </td></tr> <tr><td>v18.0.0</td> <td><p><span>Added in: v18.0.0</span></p> </td></tr> </table> </details> </div><ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name of the test, which is displayed when reporting test results. <strong>Default:</strong> The <code>name</code> property of <code>fn</code>, or <code>'<anonymous>'</code> if <code>fn</code> does not have a name.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Configuration options for the test. The following properties are supported:<ul> <li><code>concurrency</code> {number|boolean} If a number is provided, then that many tests would run in parallel within the application thread. If <code>true</code>, all scheduled asynchronous tests run concurrently within the thread. If <code>false</code>, only one test runs at a time. If unspecified, subtests inherit this value from their parent. <strong>Default:</strong> <code>false</code>.</li> <li><code>only</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If truthy, and the test context is configured to run <code>only</code> tests, then this test will be run. Otherwise, the test is skipped. <strong>Default:</strong> <code>false</code>.</li> <li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> Allows aborting an in-progress test.</li> <li><code>skip</code> {boolean|string} If truthy, the test is skipped. If a string is provided, that string is displayed in the test results as the reason for skipping the test. <strong>Default:</strong> <code>false</code>.</li> <li><code>todo</code> {boolean|string} If truthy, the test marked as <code>TODO</code>. If a string is provided, that string is displayed in the test results as the reason why the test is <code>TODO</code>. <strong>Default:</strong> <code>false</code>.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A number of milliseconds the test will fail after. If unspecified, subtests inherit this value from their parent. <strong>Default:</strong> <code>Infinity</code>.</li> </ul> </li> <li><code>fn</code> {Function|AsyncFunction} The function under test. The first argument to this function is a <a href="#class-testcontext"><code>TestContext</code></a> object. If the test uses callbacks, the callback function is passed as the second argument. <strong>Default:</strong> A no-op function.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Resolved with <code>undefined</code> once the test completes, or immediately if the test runs within <a href="#describename-options-fn"><code>describe()</code></a>.</li> </ul> <p>The <code>test()</code> function is the value imported from the <code>test</code> module. Each invocation of this function results in reporting the test to the <a href="test.html#class-testsstream" class="type"><TestsStream></a>.</p> <p>The <code>TestContext</code> object passed to the <code>fn</code> argument can be used to perform actions related to the current test. Examples include skipping the test, adding additional diagnostic information, or creating subtests.</p> <p><code>test()</code> returns a <code>Promise</code> that resolves once the test completes. if <code>test()</code> is called within a <code>describe()</code> block, it resolve immediately. The return value can usually be discarded for top level tests. However, the return value from subtests should be used to prevent the parent test from finishing first and cancelling the subtest as shown in the following example.</p> <pre><code class="language-js">test('top level test', async (t) => { // The setTimeout() in the following subtest would cause it to outlive its // parent test if 'await' is removed on the next line. Once the parent test // completes, it will cancel any outstanding subtests. await t.test('longer running subtest', async (t) => { return new Promise((resolve, reject) => { setTimeout(resolve, 1000); }); }); }); </code></pre> <p>The <code>timeout</code> option can be used to fail the test if it takes longer than <code>timeout</code> milliseconds to complete. However, it is not a reliable mechanism for canceling tests because a running test might block the application thread and thus prevent the scheduled cancellation.</p> </section><section><h3><code>test.skip([name][, options][, fn])</code><span><a class="mark" href="#testskipname-options-fn" id="testskipname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_test_skip_name_options_fn"></a></h3> <p>Shorthand for skipping a test, same as <a href="#testname-options-fn"><code>test([name], { skip: true }[, fn])</code></a>.</p> </section><section><h3><code>test.todo([name][, options][, fn])</code><span><a class="mark" href="#testtodoname-options-fn" id="testtodoname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_test_todo_name_options_fn"></a></h3> <p>Shorthand for marking a test as <code>TODO</code>, same as <a href="#testname-options-fn"><code>test([name], { todo: true }[, fn])</code></a>.</p> </section><section><h3><code>test.only([name][, options][, fn])</code><span><a class="mark" href="#testonlyname-options-fn" id="testonlyname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_test_only_name_options_fn"></a></h3> <p>Shorthand for marking a test as <code>only</code>, same as <a href="#testname-options-fn"><code>test([name], { only: true }[, fn])</code></a>.</p> </section><section><h3><code>describe([name][, options][, fn])</code><span><a class="mark" href="#describename-options-fn" id="describename-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_describe_name_options_fn"></a></h3> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name of the suite, which is displayed when reporting test results. <strong>Default:</strong> The <code>name</code> property of <code>fn</code>, or <code>'<anonymous>'</code> if <code>fn</code> does not have a name.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Configuration options for the suite. supports the same options as <code>test([name][, options][, fn])</code>.</li> <li><code>fn</code> {Function|AsyncFunction} The function under suite declaring all subtests and subsuites. The first argument to this function is a <a href="#class-suitecontext"><code>SuiteContext</code></a> object. <strong>Default:</strong> A no-op function.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Immediately fulfilled with <code>undefined</code>.</li> </ul> <p>The <code>describe()</code> function imported from the <code>node:test</code> module. Each invocation of this function results in the creation of a Subtest. After invocation of top level <code>describe</code> functions, all top level tests and suites will execute.</p> </section><section><h3><code>describe.skip([name][, options][, fn])</code><span><a class="mark" href="#describeskipname-options-fn" id="describeskipname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_describe_skip_name_options_fn"></a></h3> <p>Shorthand for skipping a suite, same as <a href="#describename-options-fn"><code>describe([name], { skip: true }[, fn])</code></a>.</p> </section><section><h3><code>describe.todo([name][, options][, fn])</code><span><a class="mark" href="#describetodoname-options-fn" id="describetodoname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_describe_todo_name_options_fn"></a></h3> <p>Shorthand for marking a suite as <code>TODO</code>, same as <a href="#describename-options-fn"><code>describe([name], { todo: true }[, fn])</code></a>.</p> </section><section><h3><code>describe.only([name][, options][, fn])</code><span><a class="mark" href="#describeonlyname-options-fn" id="describeonlyname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_describe_only_name_options_fn"></a></h3> <div class="api_metadata"> <span>Added in: v18.15.0</span> </div><p>Shorthand for marking a suite as <code>only</code>, same as <a href="#describename-options-fn"><code>describe([name], { only: true }[, fn])</code></a>.</p> </section><section><h3><code>it([name][, options][, fn])</code><span><a class="mark" href="#itname-options-fn" id="itname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_it_name_options_fn"></a></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v18.16.0</td> <td><p>Calling <code>it()</code> is now equivalent to calling <code>test()</code>.</p> </td></tr> <tr><td>v18.6.0, v16.17.0</td> <td><p><span>Added in: v18.6.0, v16.17.0</span></p> </td></tr> </table> </details> </div><p>Shorthand for <a href="#testname-options-fn"><code>test()</code></a>.</p> <p>The <code>it()</code> function is imported from the <code>node:test</code> module.</p> </section><section><h3><code>it.skip([name][, options][, fn])</code><span><a class="mark" href="#itskipname-options-fn" id="itskipname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_it_skip_name_options_fn"></a></h3> <p>Shorthand for skipping a test, same as <a href="#testname-options-fn"><code>it([name], { skip: true }[, fn])</code></a>.</p> </section><section><h3><code>it.todo([name][, options][, fn])</code><span><a class="mark" href="#ittodoname-options-fn" id="ittodoname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_it_todo_name_options_fn"></a></h3> <p>Shorthand for marking a test as <code>TODO</code>, same as <a href="#testname-options-fn"><code>it([name], { todo: true }[, fn])</code></a>.</p> </section><section><h3><code>it.only([name][, options][, fn])</code><span><a class="mark" href="#itonlyname-options-fn" id="itonlyname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_it_only_name_options_fn"></a></h3> <div class="api_metadata"> <span>Added in: v18.15.0</span> </div><p>Shorthand for marking a test as <code>only</code>, same as <a href="#testname-options-fn"><code>it([name], { only: true }[, fn])</code></a>.</p> </section><section><h3><code>before([fn][, options])</code><span><a class="mark" href="#beforefn-options" id="beforefn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_before_fn_options"></a></h3> <div class="api_metadata"> <span>Added in: v18.8.0</span> </div><ul> <li><code>fn</code> {Function|AsyncFunction} The hook function. If the hook uses callbacks, the callback function is passed as the second argument. <strong>Default:</strong> A no-op function.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Configuration options for the hook. The following properties are supported:<ul> <li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> Allows aborting an in-progress hook.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. <strong>Default:</strong> <code>Infinity</code>.</li> </ul> </li> </ul> <p>This function is used to create a hook running before running a suite.</p> <pre><code class="language-js">describe('tests', async () => { before(() => console.log('about to run some test')); it('is a subtest', () => { assert.ok('some relevant assertion here'); }); }); </code></pre> </section><section><h3><code>after([fn][, options])</code><span><a class="mark" href="#afterfn-options" id="afterfn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_after_fn_options"></a></h3> <div class="api_metadata"> <span>Added in: v18.8.0</span> </div><ul> <li><code>fn</code> {Function|AsyncFunction} The hook function. If the hook uses callbacks, the callback function is passed as the second argument. <strong>Default:</strong> A no-op function.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Configuration options for the hook. The following properties are supported:<ul> <li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> Allows aborting an in-progress hook.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. <strong>Default:</strong> <code>Infinity</code>.</li> </ul> </li> </ul> <p>This function is used to create a hook running after running a suite.</p> <pre><code class="language-js">describe('tests', async () => { after(() => console.log('finished running tests')); it('is a subtest', () => { assert.ok('some relevant assertion here'); }); }); </code></pre> </section><section><h3><code>beforeEach([fn][, options])</code><span><a class="mark" href="#beforeeachfn-options" id="beforeeachfn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_beforeeach_fn_options"></a></h3> <div class="api_metadata"> <span>Added in: v18.8.0</span> </div><ul> <li><code>fn</code> {Function|AsyncFunction} The hook function. If the hook uses callbacks, the callback function is passed as the second argument. <strong>Default:</strong> A no-op function.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Configuration options for the hook. The following properties are supported:<ul> <li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> Allows aborting an in-progress hook.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. <strong>Default:</strong> <code>Infinity</code>.</li> </ul> </li> </ul> <p>This function is used to create a hook running before each subtest of the current suite.</p> <pre><code class="language-js">describe('tests', async () => { beforeEach(() => console.log('about to run a test')); it('is a subtest', () => { assert.ok('some relevant assertion here'); }); }); </code></pre> </section><section><h3><code>afterEach([fn][, options])</code><span><a class="mark" href="#aftereachfn-options" id="aftereachfn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_aftereach_fn_options"></a></h3> <div class="api_metadata"> <span>Added in: v18.8.0</span> </div><ul> <li><code>fn</code> {Function|AsyncFunction} The hook function. If the hook uses callbacks, the callback function is passed as the second argument. <strong>Default:</strong> A no-op function.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Configuration options for the hook. The following properties are supported:<ul> <li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> Allows aborting an in-progress hook.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. <strong>Default:</strong> <code>Infinity</code>.</li> </ul> </li> </ul> <p>This function is used to create a hook running after each subtest of the current test.</p> <pre><code class="language-js">describe('tests', async () => { afterEach(() => console.log('finished running a test')); it('is a subtest', () => { assert.ok('some relevant assertion here'); }); }); </code></pre> </section><section><h3>Class: <code>MockFunctionContext</code><span><a class="mark" href="#class-mockfunctioncontext" id="class-mockfunctioncontext">#</a></span><a aria-hidden="true" class="legacy" id="test_class_mockfunctioncontext"></a></h3> <div class="api_metadata"> <span>Added in: v18.13.0</span> </div><p>The <code>MockFunctionContext</code> class is used to inspect or manipulate the behavior of mocks created via the <a href="#class-mocktracker"><code>MockTracker</code></a> APIs.</p> <h4><code>ctx.calls</code><span><a class="mark" href="#ctxcalls" id="ctxcalls">#</a></span><a aria-hidden="true" class="legacy" id="test_ctx_calls"></a></h4> <div class="api_metadata"> <span>Added in: v18.13.0</span> </div><ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li> </ul> <p>A getter that returns a copy of the internal array used to track calls to the mock. Each entry in the array is an object with the following properties.</p> <ul> <li><code>arguments</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> An array of the arguments passed to the mock function.</li> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> If the mocked function threw then this property contains the thrown value. <strong>Default:</strong> <code>undefined</code>.</li> <li><code>result</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The value returned by the mocked function.</li> <li><code>stack</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> An <code>Error</code> object whose stack can be used to determine the callsite of the mocked function invocation.</li> <li><code>target</code> {Function|undefined} If the mocked function is a constructor, this field contains the class being constructed. Otherwise this will be <code>undefined</code>.</li> <li><code>this</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The mocked function's <code>this</code> value.</li> </ul> <h4><code>ctx.callCount()</code><span><a class="mark" href="#ctxcallcount" id="ctxcallcount">#</a></span><a aria-hidden="true" class="legacy" id="test_ctx_callcount"></a></h4> <div class="api_metadata"> <span>Added in: v18.13.0</span> </div><ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of times that this mock has been invoked.</li> </ul> <p>This function returns the number of times that this mock has been invoked. This function is more efficient than checking <code>ctx.calls.length</code> because <code>ctx.calls</code> is a getter that creates a copy of the internal call tracking array.</p> <h4><code>ctx.mockImplementation(implementation)</code><span><a class="mark" href="#ctxmockimplementationimplementation" id="ctxmockimplementationimplementation">#</a></span><a aria-hidden="true" class="legacy" id="test_ctx_mockimplementation_implementation"></a></h4> <div class="api_metadata"> <span>Added in: v18.13.0</span> </div><ul> <li><code>implementation</code> {Function|AsyncFunction} The function to be used as the mock's new implementation.</li> </ul> <p>This function is used to change the behavior of an existing mock.</p> <p>The following example creates a mock function using <code>t.mock.fn()</code>, calls the mock function, and then changes the mock implementation to a different function.</p> <pre><code class="language-js">test('changes a mock behavior', (t) => { let cnt = 0; function addOne() { cnt++; return cnt; } function addTwo() { cnt += 2; return cnt; } const fn = t.mock.fn(addOne); assert.strictEqual(fn(), 1); fn.mock.mockImplementation(addTwo); assert.strictEqual(fn(), 3); assert.strictEqual(fn(), 5); }); </code></pre> <h4><code>ctx.mockImplementationOnce(implementation[, onCall])</code><span><a class="mark" href="#ctxmockimplementationonceimplementation-oncall" id="ctxmockimplementationonceimplementation-oncall">#</a></span><a aria-hidden="true" class="legacy" id="test_ctx_mockimplementationonce_implementation_oncall"></a></h4> <div class="api_metadata"> <span>Added in: v18.13.0</span> </div><ul> <li><code>implementation</code> {Function|AsyncFunction} The function to be used as the mock's implementation for the invocation number specified by <code>onCall</code>.</li> <li><code>onCall</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The invocation number that will use <code>implementation</code>. If the specified invocation has already occurred then an exception is thrown. <strong>Default:</strong> The number of the next invocation.</li> </ul> <p>This function is used to change the behavior of an existing mock for a single invocation. Once invocation <code>onCall</code> has occurred, the mock will revert to whatever behavior it would have used had <code>mockImplementationOnce()</code> not been called.</p> <p>The following example creates a mock function using <code>t.mock.fn()</code>, calls the mock function, changes the mock implementation to a different function for the next invocation, and then resumes its previous behavior.</p> <pre><code class="language-js">test('changes a mock behavior once', (t) => { let cnt = 0; function addOne() { cnt++; return cnt; } function addTwo() { cnt += 2; return cnt; } const fn = t.mock.fn(addOne); assert.strictEqual(fn(), 1); fn.mock.mockImplementationOnce(addTwo); assert.strictEqual(fn(), 3); assert.strictEqual(fn(), 4); }); </code></pre> <h4><code>ctx.resetCalls()</code><span><a class="mark" href="#ctxresetcalls" id="ctxresetcalls">#</a></span><a aria-hidden="true" class="legacy" id="test_ctx_resetcalls"></a></h4> <div class="api_metadata"> <span>Added in: v18.13.0</span> </div><p>Resets the call history of the mock function.</p> <h4><code>ctx.restore()</code><span><a class="mark" href="#ctxrestore" id="ctxrestore">#</a></span><a aria-hidden="true" class="legacy" id="test_ctx_restore"></a></h4> <div class="api_metadata"> <span>Added in: v18.13.0</span> </div><p>Resets the implementation of the mock function to its original behavior. The mock can still be used after calling this function.</p> </section><section><h3>Class: <code>MockTracker</code><span><a class="mark" href="#class-mocktracker" id="class-mocktracker">#</a></span><a aria-hidden="true" class="legacy" id="test_class_mocktracker"></a></h3> <div class="api_metadata"> <span>Added in: v18.13.0</span> </div><p>The <code>MockTracker</code> class is used to manage mocking functionality. The test runner module provides a top level <code>mock</code> export which is a <code>MockTracker</code> instance. Each test also provides its own <code>MockTracker</code> instance via the test context's <code>mock</code> property.</p> <h4><code>mock.fn([original[, implementation]][, options])</code><span><a class="mark" href="#mockfnoriginal-implementation-options" id="mockfnoriginal-implementation-options">#</a></span><a aria-hidden="true" class="legacy" id="test_mock_fn_original_implementation_options"></a></h4> <div class="api_metadata"> <span>Added in: v18.13.0</span> </div><ul> <li><code>original</code> {Function|AsyncFunction} An optional function to create a mock on. <strong>Default:</strong> A no-op function.</li> <li><code>implementation</code> {Function|AsyncFunction} An optional function used as the mock implementation for <code>original</code>. This is useful for creating mocks that exhibit one behavior for a specified number of calls and then restore the behavior of <code>original</code>. <strong>Default:</strong> The function specified by <code>original</code>.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Optional configuration options for the mock function. The following properties are supported:<ul> <li><code>times</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of times that the mock will use the behavior of <code>implementation</code>. Once the mock function has been called <code>times</code> times, it will automatically restore the behavior of <code>original</code>. This value must be an integer greater than zero. <strong>Default:</strong> <code>Infinity</code>.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy" class="type"><Proxy></a> The mocked function. The mocked function contains a special <code>mock</code> property, which is an instance of <a href="#class-mockfunctioncontext"><code>MockFunctionContext</code></a>, and can be used for inspecting and changing the behavior of the mocked function.</li> </ul> <p>This function is used to create a mock function.</p> <p>The following example creates a mock function that increments a counter by one on each invocation. The <code>times</code> option is used to modify the mock behavior such that the first two invocations add two to the counter instead of one.</p> <pre><code class="language-js">test('mocks a counting function', (t) => { let cnt = 0; function addOne() { cnt++; return cnt; } function addTwo() { cnt += 2; return cnt; } const fn = t.mock.fn(addOne, addTwo, { times: 2 }); assert.strictEqual(fn(), 2); assert.strictEqual(fn(), 4); assert.strictEqual(fn(), 5); assert.strictEqual(fn(), 6); }); </code></pre> <h4><code>mock.getter(object, methodName[, implementation][, options])</code><span><a class="mark" href="#mockgetterobject-methodname-implementation-options" id="mockgetterobject-methodname-implementation-options">#</a></span><a aria-hidden="true" class="legacy" id="test_mock_getter_object_methodname_implementation_options"></a></h4> <div class="api_metadata"> <span>Added in: v18.13.0</span> </div><p>This function is syntax sugar for <a href="#mockmethodobject-methodname-implementation-options"><code>MockTracker.method</code></a> with <code>options.getter</code> set to <code>true</code>.</p> <h4><code>mock.method(object, methodName[, implementation][, options])</code><span><a class="mark" href="#mockmethodobject-methodname-implementation-options" id="mockmethodobject-methodname-implementation-options">#</a></span><a aria-hidden="true" class="legacy" id="test_mock_method_object_methodname_implementation_options"></a></h4> <div class="api_metadata"> <span>Added in: v18.13.0</span> </div><ul> <li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The object whose method is being mocked.</li> <li><code>methodName</code> {string|symbol} The identifier of the method on <code>object</code> to mock. If <code>object[methodName]</code> is not a function, an error is thrown.</li> <li><code>implementation</code> {Function|AsyncFunction} An optional function used as the mock implementation for <code>object[methodName]</code>. <strong>Default:</strong> The original method specified by <code>object[methodName]</code>.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Optional configuration options for the mock method. The following properties are supported:<ul> <li><code>getter</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, <code>object[methodName]</code> is treated as a getter. This option cannot be used with the <code>setter</code> option. <strong>Default:</strong> false.</li> <li><code>setter</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, <code>object[methodName]</code> is treated as a setter. This option cannot be used with the <code>getter</code> option. <strong>Default:</strong> false.</li> <li><code>times</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of times that the mock will use the behavior of <code>implementation</code>. Once the mocked method has been called <code>times</code> times, it will automatically restore the original behavior. This value must be an integer greater than zero. <strong>Default:</strong> <code>Infinity</code>.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy" class="type"><Proxy></a> The mocked method. The mocked method contains a special <code>mock</code> property, which is an instance of <a href="#class-mockfunctioncontext"><code>MockFunctionContext</code></a>, and can be used for inspecting and changing the behavior of the mocked method.</li> </ul> <p>This function is used to create a mock on an existing object method. The following example demonstrates how a mock is created on an existing object method.</p> <pre><code class="language-js">test('spies on an object method', (t) => { const number = { value: 5, subtract(a) { return this.value - a; }, }; t.mock.method(number, 'subtract'); assert.strictEqual(number.subtract.mock.calls.length, 0); assert.strictEqual(number.subtract(3), 2); assert.strictEqual(number.subtract.mock.calls.length, 1); const call = number.subtract.mock.calls[0]; assert.deepStrictEqual(call.arguments, [3]); assert.strictEqual(call.result, 2); assert.strictEqual(call.error, undefined); assert.strictEqual(call.target, undefined); assert.strictEqual(call.this, number); }); </code></pre> <h4><code>mock.reset()</code><span><a class="mark" href="#mockreset" id="mockreset">#</a></span><a aria-hidden="true" class="legacy" id="test_mock_reset"></a></h4> <div class="api_metadata"> <span>Added in: v18.13.0</span> </div><p>This function restores the default behavior of all mocks that were previously created by this <code>MockTracker</code> and disassociates the mocks from the <code>MockTracker</code> instance. Once disassociated, the mocks can still be used, but the <code>MockTracker</code> instance can no longer be used to reset their behavior or otherwise interact with them.</p> <p>After each test completes, this function is called on the test context's <code>MockTracker</code>. If the global <code>MockTracker</code> is used extensively, calling this function manually is recommended.</p> <h4><code>mock.restoreAll()</code><span><a class="mark" href="#mockrestoreall" id="mockrestoreall">#</a></span><a aria-hidden="true" class="legacy" id="test_mock_restoreall"></a></h4> <div class="api_metadata"> <span>Added in: v18.13.0</span> </div><p>This function restores the default behavior of all mocks that were previously created by this <code>MockTracker</code>. Unlike <code>mock.reset()</code>, <code>mock.restoreAll()</code> does not disassociate the mocks from the <code>MockTracker</code> instance.</p> <h4><code>mock.setter(object, methodName[, implementation][, options])</code><span><a class="mark" href="#mocksetterobject-methodname-implementation-options" id="mocksetterobject-methodname-implementation-options">#</a></span><a aria-hidden="true" class="legacy" id="test_mock_setter_object_methodname_implementation_options"></a></h4> <div class="api_metadata"> <span>Added in: v18.13.0</span> </div><p>This function is syntax sugar for <a href="#mockmethodobject-methodname-implementation-options"><code>MockTracker.method</code></a> with <code>options.setter</code> set to <code>true</code>.</p> </section><section><h3>Class: <code>MockTimers</code><span><a class="mark" href="#class-mocktimers" id="class-mocktimers">#</a></span><a aria-hidden="true" class="legacy" id="test_class_mocktimers"></a></h3> <div class="api_metadata"> <span>Added in: v18.19.0</span> </div><blockquote> <p>Stability: 1 - Experimental</p> </blockquote> <p>Mocking timers is a technique commonly used in software testing to simulate and control the behavior of timers, such as <code>setInterval</code> and <code>setTimeout</code>, without actually waiting for the specified time intervals.</p> <p>The <a href="#class-mocktracker"><code>MockTracker</code></a> provides a top-level <code>timers</code> export which is a <code>MockTimers</code> instance.</p> <h4><code>timers.enable([timers])</code><span><a class="mark" href="#timersenabletimers" id="timersenabletimers">#</a></span><a aria-hidden="true" class="legacy" id="test_timers_enable_timers"></a></h4> <div class="api_metadata"> <span>Added in: v18.19.0</span> </div><p>Enables timer mocking for the specified timers.</p> <ul> <li><code>timers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> An optional array containing the timers to mock. The currently supported timer values are <code>'setInterval'</code>, <code>'setTimeout'</code>, and <code>'setImmediate'</code>. If no value is provided, all timers (<code>'setInterval'</code>, <code>'clearInterval'</code>, <code>'setTimeout'</code>, <code>'clearTimeout'</code>, <code>'setImmediate'</code>, and <code>'clearImmediate'</code>) will be mocked by default.</li> </ul> <p><strong>Note:</strong> When you enable mocking for a specific timer, its associated clear function will also be implicitly mocked.</p> <p>Example usage:</p> <pre><code class="language-mjs">import { mock } from 'node:test'; mock.timers.enable(['setInterval']); </code></pre> <pre><code class="language-cjs">const { mock } = require('node:test'); mock.timers.enable(['setInterval']); </code></pre> <p>The above example enables mocking for the <code>setInterval</code> timer and implicitly mocks the <code>clearInterval</code> function. Only the <code>setInterval</code> and <code>clearInterval</code> functions from <a href="./timers.html">node:timers</a>, <a href="./timers.html#timers-promises-api">node:timers/promises</a>, and <code>globalThis</code> will be mocked.</p> <p>Alternatively, if you call <code>mock.timers.enable()</code> without any parameters:</p> <p>All timers (<code>'setInterval'</code>, <code>'clearInterval'</code>, <code>'setTimeout'</code>, and <code>'clearTimeout'</code>) will be mocked. The <code>setInterval</code>, <code>clearInterval</code>, <code>setTimeout</code>, and <code>clearTimeout</code> functions from <code>node:timers</code>, <code>node:timers/promises</code>, and <code>globalThis</code> will be mocked.</p> <h4><code>timers.reset()</code><span><a class="mark" href="#timersreset" id="timersreset">#</a></span><a aria-hidden="true" class="legacy" id="test_timers_reset"></a></h4> <div class="api_metadata"> <span>Added in: v18.19.0</span> </div><p>This function restores the default behavior of all mocks that were previously created by this <code>MockTimers</code> instance and disassociates the mocks from the <code>MockTracker</code> instance.</p> <p><strong>Note:</strong> After each test completes, this function is called on the test context's <code>MockTracker</code>.</p> <pre><code class="language-mjs">import { mock } from 'node:test'; mock.timers.reset(); </code></pre> <pre><code class="language-cjs">const { mock } = require('node:test'); mock.timers.reset(); </code></pre> <h4><code>timers[Symbol.dispose]()</code><span><a class="mark" href="#timerssymboldispose" id="timerssymboldispose">#</a></span><a aria-hidden="true" class="legacy" id="test_timers_symbol_dispose"></a></h4> <p>Calls <code>timers.reset()</code>.</p> <h4><code>timers.tick(milliseconds)</code><span><a class="mark" href="#timerstickmilliseconds" id="timerstickmilliseconds">#</a></span><a aria-hidden="true" class="legacy" id="test_timers_tick_milliseconds"></a></h4> <div class="api_metadata"> <span>Added in: v18.19.0</span> </div><p>Advances time for all mocked timers.</p> <ul> <li><code>milliseconds</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The amount of time, in milliseconds, to advance the timers.</li> </ul> <p><strong>Note:</strong> This diverges from how <code>setTimeout</code> in Node.js behaves and accepts only positive numbers. In Node.js, <code>setTimeout</code> with negative numbers is only supported for web compatibility reasons.</p> <p>The following example mocks a <code>setTimeout</code> function and by using <code>.tick</code> advances in time triggering all pending timers.</p> <pre><code class="language-mjs">import assert from 'node:assert'; import { test } from 'node:test'; test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { const fn = context.mock.fn(); context.mock.timers.enable(['setTimeout']); setTimeout(fn, 9999); assert.strictEqual(fn.mock.callCount(), 0); // Advance in time context.mock.timers.tick(9999); assert.strictEqual(fn.mock.callCount(), 1); }); </code></pre> <pre><code class="language-cjs">const assert = require('node:assert'); const { test } = require('node:test'); test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { const fn = context.mock.fn(); context.mock.timers.enable(['setTimeout']); setTimeout(fn, 9999); assert.strictEqual(fn.mock.callCount(), 0); // Advance in time context.mock.timers.tick(9999); assert.strictEqual(fn.mock.callCount(), 1); }); </code></pre> <p>Alternativelly, the <code>.tick</code> function can be called many times</p> <pre><code class="language-mjs">import assert from 'node:assert'; import { test } from 'node:test'; test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { const fn = context.mock.fn(); context.mock.timers.enable(['setTimeout']); const nineSecs = 9000; setTimeout(fn, nineSecs); const twoSeconds = 3000; context.mock.timers.tick(twoSeconds); context.mock.timers.tick(twoSeconds); context.mock.timers.tick(twoSeconds); assert.strictEqual(fn.mock.callCount(), 1); }); </code></pre> <pre><code class="language-cjs">const assert = require('node:assert'); const { test } = require('node:test'); test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { const fn = context.mock.fn(); context.mock.timers.enable(['setTimeout']); const nineSecs = 9000; setTimeout(fn, nineSecs); const twoSeconds = 3000; context.mock.timers.tick(twoSeconds); context.mock.timers.tick(twoSeconds); context.mock.timers.tick(twoSeconds); assert.strictEqual(fn.mock.callCount(), 1); }); </code></pre> <h5>Using clear functions<span><a class="mark" href="#using-clear-functions" id="using-clear-functions">#</a></span><a aria-hidden="true" class="legacy" id="test_using_clear_functions"></a></h5> <p>As mentioned, all clear functions from timers (<code>clearTimeout</code> and <code>clearInterval</code>) are implicity mocked. Take a look at this example using <code>setTimeout</code>:</p> <pre><code class="language-mjs">import assert from 'node:assert'; import { test } from 'node:test'; test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { const fn = context.mock.fn(); // Optionally choose what to mock context.mock.timers.enable(['setTimeout']); const id = setTimeout(fn, 9999); // Implicity mocked as well clearTimeout(id); context.mock.timers.tick(9999); // As that setTimeout was cleared the mock function will never be called assert.strictEqual(fn.mock.callCount(), 0); }); </code></pre> <pre><code class="language-cjs">const assert = require('node:assert'); const { test } = require('node:test'); test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { const fn = context.mock.fn(); // Optionally choose what to mock context.mock.timers.enable(['setTimeout']); const id = setTimeout(fn, 9999); // Implicity mocked as well clearTimeout(id); context.mock.timers.tick(9999); // As that setTimeout was cleared the mock function will never be called assert.strictEqual(fn.mock.callCount(), 0); }); </code></pre> <h5>Working with Node.js timers modules<span><a class="mark" href="#working-with-nodejs-timers-modules" id="working-with-nodejs-timers-modules">#</a></span><a aria-hidden="true" class="legacy" id="test_working_with_node_js_timers_modules"></a></h5> <p>Once you enable mocking timers, <a href="./timers.html">node:timers</a>, <a href="./timers.html#timers-promises-api">node:timers/promises</a> modules, and timers from the Node.js global context are enabled:</p> <p><strong>Note:</strong> Destructuring functions such as <code>import { setTimeout } from 'node:timers'</code> is currently not supported by this API.</p> <pre><code class="language-mjs">import assert from 'node:assert'; import { test } from 'node:test'; import nodeTimers from 'node:timers'; import nodeTimersPromises from 'node:timers/promises'; test('mocks setTimeout to be executed synchronously without having to actually wait for it', async (context) => { const globalTimeoutObjectSpy = context.mock.fn(); const nodeTimerSpy = context.mock.fn(); const nodeTimerPromiseSpy = context.mock.fn(); // Optionally choose what to mock context.mock.timers.enable(['setTimeout']); setTimeout(globalTimeoutObjectSpy, 9999); nodeTimers.setTimeout(nodeTimerSpy, 9999); const promise = nodeTimersPromises.setTimeout(9999).then(nodeTimerPromiseSpy); // Advance in time context.mock.timers.tick(9999); assert.strictEqual(globalTimeoutObjectSpy.mock.callCount(), 1); assert.strictEqual(nodeTimerSpy.mock.callCount(), 1); await promise; assert.strictEqual(nodeTimerPromiseSpy.mock.callCount(), 1); }); </code></pre> <pre><code class="language-cjs">const assert = require('node:assert'); const { test } = require('node:test'); const nodeTimers = require('node:timers'); const nodeTimersPromises = require('node:timers/promises'); test('mocks setTimeout to be executed synchronously without having to actually wait for it', async (context) => { const globalTimeoutObjectSpy = context.mock.fn(); const nodeTimerSpy = context.mock.fn(); const nodeTimerPromiseSpy = context.mock.fn(); // Optionally choose what to mock context.mock.timers.enable(['setTimeout']); setTimeout(globalTimeoutObjectSpy, 9999); nodeTimers.setTimeout(nodeTimerSpy, 9999); const promise = nodeTimersPromises.setTimeout(9999).then(nodeTimerPromiseSpy); // Advance in time context.mock.timers.tick(9999); assert.strictEqual(globalTimeoutObjectSpy.mock.callCount(), 1); assert.strictEqual(nodeTimerSpy.mock.callCount(), 1); await promise; assert.strictEqual(nodeTimerPromiseSpy.mock.callCount(), 1); }); </code></pre> <p>In Node.js, <code>setInterval</code> from <a href="./timers.html#timers-promises-api">node:timers/promises</a> is an <code>AsyncGenerator</code> and is also supported by this API:</p> <pre><code class="language-mjs">import assert from 'node:assert'; import { test } from 'node:test'; import nodeTimersPromises from 'node:timers/promises'; test('should tick five times testing a real use case', async (context) => { context.mock.timers.enable(['setInterval']); const expectedIterations = 3; const interval = 1000; const startedAt = Date.now(); async function run() { const times = []; for await (const time of nodeTimersPromises.setInterval(interval, startedAt)) { times.push(time); if (times.length === expectedIterations) break; } return times; } const r = run(); context.mock.timers.tick(interval); context.mock.timers.tick(interval); context.mock.timers.tick(interval); const timeResults = await r; assert.strictEqual(timeResults.length, expectedIterations); for (let it = 1; it < expectedIterations; it++) { assert.strictEqual(timeResults[it - 1], startedAt + (interval * it)); } }); </code></pre> <pre><code class="language-cjs">const assert = require('node:assert'); const { test } = require('node:test'); const nodeTimersPromises = require('node:timers/promises'); test('should tick five times testing a real use case', async (context) => { context.mock.timers.enable(['setInterval']); const expectedIterations = 3; const interval = 1000; const startedAt = Date.now(); async function run() { const times = []; for await (const time of nodeTimersPromises.setInterval(interval, startedAt)) { times.push(time); if (times.length === expectedIterations) break; } return times; } const r = run(); context.mock.timers.tick(interval); context.mock.timers.tick(interval); context.mock.timers.tick(interval); const timeResults = await r; assert.strictEqual(timeResults.length, expectedIterations); for (let it = 1; it < expectedIterations; it++) { assert.strictEqual(timeResults[it - 1], startedAt + (interval * it)); } }); </code></pre> <h4><code>timers.runAll()</code><span><a class="mark" href="#timersrunall" id="timersrunall">#</a></span><a aria-hidden="true" class="legacy" id="test_timers_runall"></a></h4> <div class="api_metadata"> <span>Added in: v18.19.0</span> </div><p>Triggers all pending mocked timers immediately.</p> <p>The example below triggers all pending timers immediately, causing them to execute without any delay.</p> <pre><code class="language-mjs">import assert from 'node:assert'; import { test } from 'node:test'; test('runAll functions following the given order', (context) => { context.mock.timers.enable(['setTimeout']); const results = []; setTimeout(() => results.push(1), 9999); // Notice that if both timers have the same timeout, // the order of execution is guaranteed setTimeout(() => results.push(3), 8888); setTimeout(() => results.push(2), 8888); assert.deepStrictEqual(results, []); context.mock.timers.runAll(); assert.deepStrictEqual(results, [3, 2, 1]); }); </code></pre> <pre><code class="language-cjs">const assert = require('node:assert'); const { test } = require('node:test'); test('runAll functions following the given order', (context) => { context.mock.timers.enable(['setTimeout']); const results = []; setTimeout(() => results.push(1), 9999); // Notice that if both timers have the same timeout, // the order of execution is guaranteed setTimeout(() => results.push(3), 8888); setTimeout(() => results.push(2), 8888); assert.deepStrictEqual(results, []); context.mock.timers.runAll(); assert.deepStrictEqual(results, [3, 2, 1]); }); </code></pre> <p><strong>Note:</strong> The <code>runAll()</code> function is specifically designed for triggering timers in the context of timer mocking. It does not have any effect on real-time system clocks or actual timers outside of the mocking environment.</p> </section><section><h3>Class: <code>TestsStream</code><span><a class="mark" href="#class-testsstream" id="class-testsstream">#</a></span><a aria-hidden="true" class="legacy" id="test_class_testsstream"></a></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v18.17.0</td> <td><p>added type to test:pass and test:fail events for when the test is a suite.</p> </td></tr> <tr><td>v18.9.0, v16.19.0</td> <td><p><span>Added in: v18.9.0, v16.19.0</span></p> </td></tr> </table> </details> </div><ul> <li>Extends <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a></li> </ul> <p>A successful call to <a href="#runoptions"><code>run()</code></a> method will return a new <a href="test.html#class-testsstream" class="type"><TestsStream></a> object, streaming a series of events representing the execution of the tests. <code>TestsStream</code> will emit events, in the order of the tests definition</p> <h4>Event: <code>'test:coverage'</code><span><a class="mark" href="#event-testcoverage" id="event-testcoverage">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_coverage"></a></h4> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul> <li><code>summary</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object containing the coverage report.<ul> <li><code>files</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> An array of coverage reports for individual files. Each report is an object with the following schema:<ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The absolute path of the file.</li> <li><code>totalLineCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The total number of lines.</li> <li><code>totalBranchCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The total number of branches.</li> <li><code>totalFunctionCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The total number of functions.</li> <li><code>coveredLineCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of covered lines.</li> <li><code>coveredBranchCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of covered branches.</li> <li><code>coveredFunctionCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of covered functions.</li> <li><code>coveredLinePercent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The percentage of lines covered.</li> <li><code>coveredBranchPercent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The percentage of branches covered.</li> <li><code>coveredFunctionPercent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The percentage of functions covered.</li> <li><code>uncoveredLineNumbers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> An array of integers representing line numbers that are uncovered.</li> </ul> </li> <li><code>totals</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object containing a summary of coverage for all files.<ul> <li><code>totalLineCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The total number of lines.</li> <li><code>totalBranchCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The total number of branches.</li> <li><code>totalFunctionCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The total number of functions.</li> <li><code>coveredLineCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of covered lines.</li> <li><code>coveredBranchCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of covered branches.</li> <li><code>coveredFunctionCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of covered functions.</li> <li><code>coveredLinePercent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The percentage of lines covered.</li> <li><code>coveredBranchPercent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The percentage of branches covered.</li> <li><code>coveredFunctionPercent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The percentage of functions covered.</li> </ul> </li> <li><code>workingDirectory</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The working directory when code coverage began. This is useful for displaying relative path names in case the tests changed the working directory of the Node.js process.</li> </ul> </li> <li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The nesting level of the test.</li> </ul> </li> </ul> <p>Emitted when code coverage is enabled and all tests have completed.</p> <h4>Event: <code>'test:dequeue'</code><span><a class="mark" href="#event-testdequeue" id="event-testdequeue">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_dequeue"></a></h4> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul> <li><code>column</code> {number|undefined} The column number where the test is defined, or <code>undefined</code> if the test was run through the REPL.</li> <li><code>file</code> {string|undefined} The path of the test file, <code>undefined</code> if test was run through the REPL.</li> <li><code>line</code> {number|undefined} The line number where the test is defined, or <code>undefined</code> if the test was run through the REPL.</li> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The test name.</li> <li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The nesting level of the test.</li> </ul> </li> </ul> <p>Emitted when a test is dequeued, right before it is executed.</p> <h4>Event: <code>'test:diagnostic'</code><span><a class="mark" href="#event-testdiagnostic" id="event-testdiagnostic">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_diagnostic"></a></h4> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul> <li><code>column</code> {number|undefined} The column number where the test is defined, or <code>undefined</code> if the test was run through the REPL.</li> <li><code>file</code> {string|undefined} The path of the test file, <code>undefined</code> if test was run through the REPL.</li> <li><code>line</code> {number|undefined} The line number where the test is defined, or <code>undefined</code> if the test was run through the REPL.</li> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The diagnostic message.</li> <li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The nesting level of the test.</li> </ul> </li> </ul> <p>Emitted when <a href="#contextdiagnosticmessage"><code>context.diagnostic</code></a> is called.</p> <h4>Event: <code>'test:enqueue'</code><span><a class="mark" href="#event-testenqueue" id="event-testenqueue">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_enqueue"></a></h4> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul> <li><code>column</code> {number|undefined} The column number where the test is defined, or <code>undefined</code> if the test was run through the REPL.</li> <li><code>file</code> {string|undefined} The path of the test file, <code>undefined</code> if test was run through the REPL.</li> <li><code>line</code> {number|undefined} The line number where the test is defined, or <code>undefined</code> if the test was run through the REPL.</li> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The test name.</li> <li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The nesting level of the test.</li> </ul> </li> </ul> <p>Emitted when a test is enqueued for execution.</p> <h4>Event: <code>'test:fail'</code><span><a class="mark" href="#event-testfail" id="event-testfail">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_fail"></a></h4> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul> <li><code>column</code> {number|undefined} The column number where the test is defined, or <code>undefined</code> if the test was run through the REPL.</li> <li><code>details</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Additional execution metadata.<ul> <li><code>duration_ms</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The duration of the test in milliseconds.</li> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> An error wrapping the error thrown by the test.<ul> <li><code>cause</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> The actual error thrown by the test.</li> </ul> </li> <li><code>type</code> {string|undefined} The type of the test, used to denote whether this is a suite.</li> </ul> </li> <li><code>file</code> {string|undefined} The path of the test file, <code>undefined</code> if test was run through the REPL.</li> <li><code>line</code> {number|undefined} The line number where the test is defined, or <code>undefined</code> if the test was run through the REPL.</li> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The test name.</li> <li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The nesting level of the test.</li> <li><code>testNumber</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The ordinal number of the test.</li> <li><code>todo</code> {string|boolean|undefined} Present if <a href="#contexttodomessage"><code>context.todo</code></a> is called</li> <li><code>skip</code> {string|boolean|undefined} Present if <a href="#contextskipmessage"><code>context.skip</code></a> is called</li> </ul> </li> </ul> <p>Emitted when a test fails.</p> <h4>Event: <code>'test:pass'</code><span><a class="mark" href="#event-testpass" id="event-testpass">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_pass"></a></h4> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul> <li><code>column</code> {number|undefined} The column number where the test is defined, or <code>undefined</code> if the test was run through the REPL.</li> <li><code>details</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Additional execution metadata.<ul> <li><code>duration_ms</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The duration of the test in milliseconds.</li> <li><code>type</code> {string|undefined} The type of the test, used to denote whether this is a suite.</li> </ul> </li> <li><code>file</code> {string|undefined} The path of the test file, <code>undefined</code> if test was run through the REPL.</li> <li><code>line</code> {number|undefined} The line number where the test is defined, or <code>undefined</code> if the test was run through the REPL.</li> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The test name.</li> <li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The nesting level of the test.</li> <li><code>testNumber</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The ordinal number of the test.</li> <li><code>todo</code> {string|boolean|undefined} Present if <a href="#contexttodomessage"><code>context.todo</code></a> is called</li> <li><code>skip</code> {string|boolean|undefined} Present if <a href="#contextskipmessage"><code>context.skip</code></a> is called</li> </ul> </li> </ul> <p>Emitted when a test passes.</p> <h4>Event: <code>'test:plan'</code><span><a class="mark" href="#event-testplan" id="event-testplan">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_plan"></a></h4> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul> <li><code>column</code> {number|undefined} The column number where the test is defined, or <code>undefined</code> if the test was run through the REPL.</li> <li><code>file</code> {string|undefined} The path of the test file, <code>undefined</code> if test was run through the REPL.</li> <li><code>line</code> {number|undefined} The line number where the test is defined, or <code>undefined</code> if the test was run through the REPL.</li> <li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The nesting level of the test.</li> <li><code>count</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of subtests that have ran.</li> </ul> </li> </ul> <p>Emitted when all subtests have completed for a given test.</p> <h4>Event: <code>'test:start'</code><span><a class="mark" href="#event-teststart" id="event-teststart">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_start"></a></h4> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul> <li><code>column</code> {number|undefined} The column number where the test is defined, or <code>undefined</code> if the test was run through the REPL.</li> <li><code>file</code> {string|undefined} The path of the test file, <code>undefined</code> if test was run through the REPL.</li> <li><code>line</code> {number|undefined} The line number where the test is defined, or <code>undefined</code> if the test was run through the REPL.</li> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The test name.</li> <li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The nesting level of the test.</li> </ul> </li> </ul> <p>Emitted when a test starts reporting its own and its subtests status. This event is guaranteed to be emitted in the same order as the tests are defined.</p> <h4>Event: <code>'test:stderr'</code><span><a class="mark" href="#event-teststderr" id="event-teststderr">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_stderr"></a></h4> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul> <li><code>column</code> {number|undefined} The column number where the test is defined, or <code>undefined</code> if the test was run through the REPL.</li> <li><code>file</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The path of the test file.</li> <li><code>line</code> {number|undefined} The line number where the test is defined, or <code>undefined</code> if the test was run through the REPL.</li> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The message written to <code>stderr</code>.</li> </ul> </li> </ul> <p>Emitted when a running test writes to <code>stderr</code>. This event is only emitted if <code>--test</code> flag is passed.</p> <h4>Event: <code>'test:stdout'</code><span><a class="mark" href="#event-teststdout" id="event-teststdout">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_stdout"></a></h4> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul> <li><code>column</code> {number|undefined} The column number where the test is defined, or <code>undefined</code> if the test was run through the REPL.</li> <li><code>file</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The path of the test file.</li> <li><code>line</code> {number|undefined} The line number where the test is defined, or <code>undefined</code> if the test was run through the REPL.</li> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The message written to <code>stdout</code>.</li> </ul> </li> </ul> <p>Emitted when a running test writes to <code>stdout</code>. This event is only emitted if <code>--test</code> flag is passed.</p> <h4>Event: <code>'test:watch:drained'</code><span><a class="mark" href="#event-testwatchdrained" id="event-testwatchdrained">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_watch_drained"></a></h4> <p>Emitted when no more tests are queued for execution in watch mode.</p> </section><section><h3>Class: <code>TestContext</code><span><a class="mark" href="#class-testcontext" id="class-testcontext">#</a></span><a aria-hidden="true" class="legacy" id="test_class_testcontext"></a></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v18.17.0</td> <td><p>The <code>before</code> function was added to TestContext.</p> </td></tr> <tr><td>v18.0.0</td> <td><p><span>Added in: v18.0.0</span></p> </td></tr> </table> </details> </div><p>An instance of <code>TestContext</code> is passed to each test function in order to interact with the test runner. However, the <code>TestContext</code> constructor is not exposed as part of the API.</p> <h4><code>context.before([fn][, options])</code><span><a class="mark" href="#contextbeforefn-options" id="contextbeforefn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_context_before_fn_options"></a></h4> <div class="api_metadata"> <span>Added in: v18.17.0</span> </div><ul> <li><code>fn</code> {Function|AsyncFunction} The hook function. The first argument to this function is a <a href="#class-testcontext"><code>TestContext</code></a> object. If the hook uses callbacks, the callback function is passed as the second argument. <strong>Default:</strong> A no-op function.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Configuration options for the hook. The following properties are supported:<ul> <li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> Allows aborting an in-progress hook.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. <strong>Default:</strong> <code>Infinity</code>.</li> </ul> </li> </ul> <p>This function is used to create a hook running before subtest of the current test.</p> <h4><code>context.beforeEach([fn][, options])</code><span><a class="mark" href="#contextbeforeeachfn-options" id="contextbeforeeachfn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_context_beforeeach_fn_options"></a></h4> <div class="api_metadata"> <span>Added in: v18.8.0</span> </div><ul> <li><code>fn</code> {Function|AsyncFunction} The hook function. The first argument to this function is a <a href="#class-testcontext"><code>TestContext</code></a> object. If the hook uses callbacks, the callback function is passed as the second argument. <strong>Default:</strong> A no-op function.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Configuration options for the hook. The following properties are supported:<ul> <li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> Allows aborting an in-progress hook.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. <strong>Default:</strong> <code>Infinity</code>.</li> </ul> </li> </ul> <p>This function is used to create a hook running before each subtest of the current test.</p> <pre><code class="language-js">test('top level test', async (t) => { t.beforeEach((t) => t.diagnostic(`about to run ${t.name}`)); await t.test( 'This is a subtest', (t) => { assert.ok('some relevant assertion here'); }, ); }); </code></pre> <h4><code>context.after([fn][, options])</code><span><a class="mark" href="#contextafterfn-options" id="contextafterfn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_context_after_fn_options"></a></h4> <div class="api_metadata"> <span>Added in: v18.13.0</span> </div><ul> <li><code>fn</code> {Function|AsyncFunction} The hook function. The first argument to this function is a <a href="#class-testcontext"><code>TestContext</code></a> object. If the hook uses callbacks, the callback function is passed as the second argument. <strong>Default:</strong> A no-op function.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Configuration options for the hook. The following properties are supported:<ul> <li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> Allows aborting an in-progress hook.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. <strong>Default:</strong> <code>Infinity</code>.</li> </ul> </li> </ul> <p>This function is used to create a hook that runs after the current test finishes.</p> <pre><code class="language-js">test('top level test', async (t) => { t.after((t) => t.diagnostic(`finished running ${t.name}`)); assert.ok('some relevant assertion here'); }); </code></pre> <h4><code>context.afterEach([fn][, options])</code><span><a class="mark" href="#contextaftereachfn-options" id="contextaftereachfn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_context_aftereach_fn_options"></a></h4> <div class="api_metadata"> <span>Added in: v18.8.0</span> </div><ul> <li><code>fn</code> {Function|AsyncFunction} The hook function. The first argument to this function is a <a href="#class-testcontext"><code>TestContext</code></a> object. If the hook uses callbacks, the callback function is passed as the second argument. <strong>Default:</strong> A no-op function.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Configuration options for the hook. The following properties are supported:<ul> <li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> Allows aborting an in-progress hook.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A number of milliseconds the hook will fail after. If unspecified, subtests inherit this value from their parent. <strong>Default:</strong> <code>Infinity</code>.</li> </ul> </li> </ul> <p>This function is used to create a hook running after each subtest of the current test.</p> <pre><code class="language-js">test('top level test', async (t) => { t.afterEach((t) => t.diagnostic(`finished running ${t.name}`)); await t.test( 'This is a subtest', (t) => { assert.ok('some relevant assertion here'); }, ); }); </code></pre> <h4><code>context.diagnostic(message)</code><span><a class="mark" href="#contextdiagnosticmessage" id="contextdiagnosticmessage">#</a></span><a aria-hidden="true" class="legacy" id="test_context_diagnostic_message"></a></h4> <div class="api_metadata"> <span>Added in: v18.0.0</span> </div><ul> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Message to be reported.</li> </ul> <p>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.</p> <pre><code class="language-js">test('top level test', (t) => { t.diagnostic('A diagnostic message'); }); </code></pre> <h4><code>context.name</code><span><a class="mark" href="#contextname" id="contextname">#</a></span><a aria-hidden="true" class="legacy" id="test_context_name"></a></h4> <div class="api_metadata"> <span>Added in: v18.8.0</span> </div><p>The name of the test.</p> <h4><code>context.runOnly(shouldRunOnlyTests)</code><span><a class="mark" href="#contextrunonlyshouldrunonlytests" id="contextrunonlyshouldrunonlytests">#</a></span><a aria-hidden="true" class="legacy" id="test_context_runonly_shouldrunonlytests"></a></h4> <div class="api_metadata"> <span>Added in: v18.0.0</span> </div><ul> <li><code>shouldRunOnlyTests</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether or not to run <code>only</code> tests.</li> </ul> <p>If <code>shouldRunOnlyTests</code> is truthy, the test context will only run tests that have the <code>only</code> option set. Otherwise, all tests are run. If Node.js was not started with the <a href="cli.html#--test-only"><code>--test-only</code></a> command-line option, this function is a no-op.</p> <pre><code class="language-js">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 }), ]); }); </code></pre> <h4><code>context.signal</code><span><a class="mark" href="#contextsignal" id="contextsignal">#</a></span><a aria-hidden="true" class="legacy" id="test_context_signal"></a></h4> <div class="api_metadata"> <span>Added in: v18.7.0</span> </div><ul> <li><a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> Can be used to abort test subtasks when the test has been aborted.</li> </ul> <pre><code class="language-js">test('top level test', async (t) => { await fetch('some/uri', { signal: t.signal }); }); </code></pre> <h4><code>context.skip([message])</code><span><a class="mark" href="#contextskipmessage" id="contextskipmessage">#</a></span><a aria-hidden="true" class="legacy" id="test_context_skip_message"></a></h4> <div class="api_metadata"> <span>Added in: v18.0.0</span> </div><ul> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Optional skip message.</li> </ul> <p>This function causes the test's output to indicate the test as skipped. If <code>message</code> is provided, it is included in the output. Calling <code>skip()</code> does not terminate execution of the test function. This function does not return a value.</p> <pre><code class="language-js">test('top level test', (t) => { // Make sure to return here as well if the test contains additional logic. t.skip('this is skipped'); }); </code></pre> <h4><code>context.todo([message])</code><span><a class="mark" href="#contexttodomessage" id="contexttodomessage">#</a></span><a aria-hidden="true" class="legacy" id="test_context_todo_message"></a></h4> <div class="api_metadata"> <span>Added in: v18.0.0</span> </div><ul> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Optional <code>TODO</code> message.</li> </ul> <p>This function adds a <code>TODO</code> directive to the test's output. If <code>message</code> is provided, it is included in the output. Calling <code>todo()</code> does not terminate execution of the test function. This function does not return a value.</p> <pre><code class="language-js">test('top level test', (t) => { // This test is marked as `TODO` t.todo('this is a todo'); }); </code></pre> <h4><code>context.test([name][, options][, fn])</code><span><a class="mark" href="#contexttestname-options-fn" id="contexttestname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_context_test_name_options_fn"></a></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tr><th>Version</th><th>Changes</th></tr> <tr><td>v18.8.0</td> <td><p>Add a <code>signal</code> option.</p> </td></tr> <tr><td>v18.7.0</td> <td><p>Add a <code>timeout</code> option.</p> </td></tr> <tr><td>v18.0.0</td> <td><p><span>Added in: v18.0.0</span></p> </td></tr> </table> </details> </div><ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name of the subtest, which is displayed when reporting test results. <strong>Default:</strong> The <code>name</code> property of <code>fn</code>, or <code>'<anonymous>'</code> if <code>fn</code> does not have a name.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Configuration options for the subtest. The following properties are supported:<ul> <li><code>concurrency</code> {number|boolean|null} If a number is provided, then that many tests would run in parallel within the application thread. If <code>true</code>, it would run all subtests in parallel. If <code>false</code>, it would only run one test at a time. If unspecified, subtests inherit this value from their parent. <strong>Default:</strong> <code>null</code>.</li> <li><code>only</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If truthy, and the test context is configured to run <code>only</code> tests, then this test will be run. Otherwise, the test is skipped. <strong>Default:</strong> <code>false</code>.</li> <li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> Allows aborting an in-progress test.</li> <li><code>skip</code> {boolean|string} If truthy, the test is skipped. If a string is provided, that string is displayed in the test results as the reason for skipping the test. <strong>Default:</strong> <code>false</code>.</li> <li><code>todo</code> {boolean|string} If truthy, the test marked as <code>TODO</code>. If a string is provided, that string is displayed in the test results as the reason why the test is <code>TODO</code>. <strong>Default:</strong> <code>false</code>.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A number of milliseconds the test will fail after. If unspecified, subtests inherit this value from their parent. <strong>Default:</strong> <code>Infinity</code>.</li> </ul> </li> <li><code>fn</code> {Function|AsyncFunction} The function under test. The first argument to this function is a <a href="#class-testcontext"><code>TestContext</code></a> object. If the test uses callbacks, the callback function is passed as the second argument. <strong>Default:</strong> A no-op function.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Resolved with <code>undefined</code> once the test completes.</li> </ul> <p>This function is used to create subtests under the current test. This function behaves in the same fashion as the top level <a href="#testname-options-fn"><code>test()</code></a> function.</p> <pre><code class="language-js">test('top level test', async (t) => { await t.test( 'This is a subtest', { only: false, skip: false, concurrency: 1, todo: false }, (t) => { assert.ok('some relevant assertion here'); }, ); }); </code></pre> </section><section><h3>Class: <code>SuiteContext</code><span><a class="mark" href="#class-suitecontext" id="class-suitecontext">#</a></span><a aria-hidden="true" class="legacy" id="test_class_suitecontext"></a></h3> <div class="api_metadata"> <span>Added in: v18.7.0</span> </div><p>An instance of <code>SuiteContext</code> is passed to each suite function in order to interact with the test runner. However, the <code>SuiteContext</code> constructor is not exposed as part of the API.</p> <h4><code>context.name</code><span><a class="mark" href="#contextname_1" id="contextname_1">#</a></span><a aria-hidden="true" class="legacy" id="test_context_name_1"></a></h4> <div class="api_metadata"> <span>Added in: v18.8.0</span> </div><p>The name of the suite.</p> <h4><code>context.signal</code><span><a class="mark" href="#contextsignal_1" id="contextsignal_1">#</a></span><a aria-hidden="true" class="legacy" id="test_context_signal_1"></a></h4> <div class="api_metadata"> <span>Added in: v18.7.0</span> </div><ul> <li><a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> Can be used to abort test subtasks when the test has been aborted.</li> </ul> </section> <!-- API END --> </div> </div> </div> </body> </html>