@hyperfrontend/ testing§
A lightweight Jest-like testing library built on native Node capabilities.
What is @hyperfrontend/testing?
@hyperfrontend/testing lets you write tests the way you would for Jest and run them on Node's built-in test runner. It adds only what Node lacks and leaves the rest to Node.
It is not Jest, which remains the fuller tool. It is for projects where Node's built-ins are enough and the familiar syntax is worth keeping.
Key Features
Describe blocks, matchers, mock functions and spies read the way a Jest suite already does
Module mocks without a transpiler
Factories, partial mocks and automocks apply under native ES modules before a spec's imports link
Advance time, drain pending timers and set the system time from inside a test
A source file no test loaded fails the run instead of quietly vanishing from the report
One preload gives browser-facing suites a jsdom window; suites that do not need it never install it
TypeScript specs as written
Node's own type stripping runs them, with extensionless imports and tsconfig path aliases resolved
The helpers suites keep rewriting
Typed object mocks, condition waits, self-cleaning temporary directories, linked windows, and stand-ins for a terminal, the standard streams and child processes
Why Use @hyperfrontend/testing?
Fewer dependencies, same habits
Node already ships a test runner, assertions, module mocking, fake timers and coverage. This package adds the shape of a Jest spec on top: one dev dependency instead of a framework, a transformer and a reporter, with nothing but Node built-ins at runtime.
A migration, not a rewrite
Jest suites keep their describe blocks, matchers and module mocks as written. Migrate a Jest suite to Node's test runner lists what does change.
Installation
npm install --save-dev @hyperfrontend/testing
Add jsdom as well only if a suite needs a DOM.
Quick Start
import { beforeEach } from 'node:test'
import { describe, expect, it, jest } from '@hyperfrontend/testing'
import { createCart } from './cart'
jest.mock('./pricing', () => ({ priceOf: () => 3 }))
describe('cart', () => {
let cart: ReturnType<typeof createCart>
beforeEach(() => {
cart = createCart()
})
it('totals the priced lines', () => {
cart.add('tea', 2)
expect(cart.total()).toBe(6)
})
it('notifies subscribers once per change', () => {
const onChange = jest.fn()
cart.subscribe(onChange)
cart.add('tea', 1)
expect(onChange).toHaveBeenCalledTimes(1)
})
})
node --import @hyperfrontend/testing/hooks --test 'src/**/*.spec.ts'
Lifecycle hooks come straight from node:test. The /hooks preload lets the spec load as TypeScript with its module mock in place.
For several environments, setup files and a coverage gate, declare a test.config.ts and run it with runProjectTests. Configure and run TypeScript tests on Node's test runner walks through a full setup.
API Overview
| Entry | What it is |
|---|---|
@hyperfrontend/testing | What a spec imports |
/hooks | The node --import preload: TypeScript resolution and mocks |
/dom | The preload that puts a jsdom window on the global |
/browser | Linked windows for cross-origin messaging, a driven ResizeObserver |
/consumer | A packed package installed and run the way a consumer runs it |
/fs | Temporary directories and fixture trees written from data |
/process | Terminal, standard stream and child process stand-ins, npm on Windows |
/runner | The config-driven runner, one node --test per environment |
/coverage | The lcov merge and the threshold gate |
/reporter | Node's spec reporter without the per-evaluation coverage noise |
Every matcher, option and signature is in the API reference.
Limitations
- No snapshots, custom matchers or watch mode. A suite that depends on them should stay on Jest.
- Coverage is V8 through Node's collector: no statements metric and no HTML report.
The full list is in Where behaviour differs from Jest.
Compatibility
Runs on
- Node.js>=22.18.0supported
- Browsersnot supported
- Web Workersnot supported
- Linuxsupported
- macOSsupported
- Windowssupported
Needs Node.js 22.18 or later: the preload installs synchronous module hooks and loads TypeScript specs through Node's own type stripping, neither of which older releases provide.
Ships as
- ESMTree-shakeable
- CJSNode and older bundlers
Peer Dependencies
| Package | Version | Type |
|---|---|---|
| jsdom | >= 26.0.0 | Optional |
Architecture Highlights§
Nothing is injected into the global scope: a spec imports what it uses. The architecture guide covers the preload, the mock registry and the coverage pipeline.
API Reference§
Module Structure
10 modules · 119 total exports
Jest-style `describe`, `it`, `expect` and `jest` on Node's built-in test runner: the surface a spec imports.
ƒ Functions
A rejection is observed by the deferred itself, so rejecting one that the code under test has not awaited yet does not end the run as an unhandled rejection. Code that does await the promise still sees it reject.
Returns
Deferred< TValue>Example
Holding an unmount open until the test lets it finish
const exit = createDeferred()
const closing = shell.close({ onUnmount: () => exit.promise })
expect(shell.isClosing()).toBe(true)
exit.resolve()
await closingMembers named in
overrides read as given, except plain functions, which become mocks that call them, so an override can be asserted on like any other member. A member overridden with undefined reads as undefined. Any other member is created as a mock returning undefined the first time it is read, at any depth. Members Object.prototype already defines, such as toString, keep their real behaviour unless overridden, and then is never invented, so the object is not mistaken for a promise. Every created mock is tracked like one made with
jest.fn, so jest.clearAllMocks and jest.resetAllMocks reach it.Returns
DeepMocked< TTarget>Examples
Handing a logger to code under test
const logger = createMock<Logger>({ getLogLevel: () => 'debug' })
connect({ logger })
expect(logger.warn).toHaveBeenCalledWith('retrying')
expect(logger.getLogLevel).toHaveBeenCalled()Scripting a nested client
const git = createMock<GitClient>()
git.log.mockReturnValue([])
git.remote.url.mockReturnValue('https://example.com/repo.git')toEqual and toStrictEqual do. Asymmetric matchers on either side decide the outcome themselves. Dates, regular expressions, errors, Maps, Sets, and typed arrays are compared by their meaningful contents rather than by enumerable properties.
Parameters
| Name | Type | Description |
|---|---|---|
§received | unknown | The value under test. |
§expected | unknown | The value it is compared against. |
§mode | EqualityMode | Whether undefined properties and prototypes are significant.(default: 'structural') |
Returns
booleanExample
Structural against strict comparison
equals({ id: 1, label: undefined }, { id: 1 }) // => true, an undefined property is ignored
equals({ id: 1, label: undefined }, { id: 1 }, 'strict') // => false
equals(new Map([[{ id: 1 }, 'a']]), new Map([[{ id: 1 }, 'a']])) // => true, keys are compared structurally tooThe promise settles from a real
setImmediate, which the event loop runs only after the microtask queue is empty, so chains of any length that were pending when it was called have settled by the time it resolves. Faking the clock does not stop it.Returns
Promise< void>Example
Letting an async handler finish before asserting
emitter.emit('message', frame)
await flushPromises()
expect(onReply).toHaveBeenCalled()toMatchObject does. Arrays must match in length and order; objects need only carry the expected keys.
Parameters
Returns
booleanExample
Accepting extra keys but not extra elements
matchesSubset({ id: 1, tags: ['a', 'b'], meta: { at: 5 } }, { tags: ['a', 'b'], meta: {} }) // => true
matchesSubset({ tags: ['a', 'b'] }, { tags: ['a'] }) // => false, arrays must match in lengthParameters
| Name | Type | Description |
|---|---|---|
§milliseconds | number | How long to wait. |
Returns
Promise< void>Example
Giving a real socket time to answer
jest.useFakeTimers()
await sleep(20) // => resolves after 20 real milliseconds, the fake clock untouchedwaitFor< TValue>( callback: ( ) => TValue | Promise< TValue>, options: WaitOptions): Promise< Awaited< TValue>>
Put the assertion inside the callback: the wait passes as soon as it holds, and when time runs out the last error is thrown as it is, so the failure reads as the assertion's own. A callback returning a promise is awaited, and a rejection counts as a throw.
Parameters
| Name | Type | Description |
|---|---|---|
§callback | ( | The check to repeat. |
§options | WaitOptions | Timeout and interval.(default: {}) |
Example
Waiting for a reply to arrive
channel.send('PING')
await waitFor(() => expect(received).toEqual(['PONG']))waitUntil< TValue>( predicate: ( ) => TValue | Promise< TValue>, options: WaitOptions): Promise< NonNullable< Awaited< TValue>>>
A throw is a failure, not a falsy result: it is raised straight away rather than retried, so a broken predicate fails fast. A predicate returning a promise is awaited.
Parameters
| Name | Type | Description |
|---|---|---|
§predicate | ( | The condition to repeat. |
§options | WaitOptions | Timeout and interval.(default: {}) |
Returns
Promise< NonNullable< Awaited< TValue>>>Examples
Waiting until both sides are connected
await waitUntil(() => channelA.isActive() && channelB.isActive())Waiting for an element and using it
const button = await waitUntil(() => document.querySelector('button'))
button.click()◆ Types
type AccessType = "get" | "set".resolves and .rejects.type AsyncAssertions = mappedtype DeepMocked = mapped & TTargetdescribe surface, including the modifiers node:test does not provide.structural reproduces Jest's toEqual: undefined-valued own properties are ignored and prototypes are not compared, so a class instance can equal a plain object. strict reproduces toStrictEqual, where both of those differences are significant.type EqualityMode = "structural" | "strict"type Expectation = Assertions & ExpectationModesjest.useFakeTimers, narrowed to the two Node's own clock honours.it surface, including the modifiers node:test does not provide. The optional trailing number is Jest's per-test timeout in milliseconds; it overrides the runner's
--test-timeout default for that one test.jest namespace object, carrying the mock, spy, and timer controls the suites use. mock and requireActual are the shapes of calls that have already happened by the time a spec body runs. The loader reads them out of the spec's source and substitutes the module before the spec's imports are linked, so what remains here is the call the spec still makes at runtime, by which point the substitution has already happened.message describes the positive expectation. The negated form is derived from it, so a matcher never has to phrase both directions.jest.Mock, so replacing one with the other is a rename rather than a re-typing.type Mock = MockFn< TArgs, TReturn>type Mocked = mapped & TTargettype MockedFunction = MockFn< Parameters< TFunction>, ReturnType< TFunction>> & TFunctionjest.mocked hands back: a function becomes its mocked signature, anything else an object of mocked members.type MockedValue = conditionalfn.mock.jest.replaceProperty, which can be given another value or put back.done-callback style.type TestBody = ( done: ( error?: unknown) => void) => unknown● Variables
it, with the Jest modifiers node:test does not provide. Import this instead of
node:test's it only in files that need .each, .failing, .concurrent, the done callback, or expect.assertions. Everywhere else, importing straight from node:test keeps the spec closer to the platform.Stand-ins for the browser surfaces a DOM-free test cannot supply: linked windows that message each other, and a `ResizeObserver` the test drives.
ƒ Functions
Use it as the target a piece of code posts to, asserting on
posted, or as the window a piece of code listens on, feeding it messages with receive.Parameters
| Name | Type | Description |
|---|---|---|
§options | FakeWindowOptions | The window's origin.(default: {}) |
Returns
FakeWindowWindow.Example
Feeding a listener a message from another origin
const host = createFakeWindow({ origin: 'https://host.test' })
const stop = listenForCommands(host)
host.receive({ type: 'PING' }, { origin: 'https://feature.test' })
expect(host.posted()).toEqual([{ type: 'PONG' }])Posting to one window delivers to that window's own listeners, with the other window as the event's
source and the other window's origin as its origin, exactly as a browser reports a message one window sent another. A post whose target origin is neither * nor the receiving window's origin is dropped, as a browser drops it, with / standing for the sender's own origin. The message is copied with structuredClone, so the receiver never shares an object with the sender; a transfer list is ignored, which leaves the posted buffers readable for assertions. By default delivery waits for a later timer task, which fake timers control.Parameters
| Name | Type | Description |
|---|---|---|
§options | WindowPairOptions | The windows' origins and when a post is delivered.(default: {}) |
Returns
unknownWindow.Example
Connecting two brokers across a frame boundary
const [host, frame] = createWindowPair({ origins: ['https://host.test', 'https://frame.test'] })
const hostBroker = createBroker({ window: host })
const frameBroker = createBroker({ window: frame })
hostBroker.addChannel('frame', frame).connect()
frameBroker.addChannel('host', host).connect()
await waitUntil(() => hostBroker.isConnected())ResizeObserver on the global whose notifications the test sends, and returns the controller that sends them. jsdom has no layout engine and so no
ResizeObserver. Observers created through this one behave like the real constructor's, observing, unobserving and disconnecting, but a callback runs only when the test calls resize, never on its own: not even the initial notification a browser sends after observe. resizeLate delivers to observers that have stopped watching the element too, the way a notification already queued when observation stopped still arrives, for code that must ignore one. The stub is installed like a stubbed global, so jest.restoreAllMocks and the runner's restoreMocks option remove it.Returns
ResizeObserverControllerExample
Driving a component that follows its container's width
const observers = installResizeObserver()
const panel = mountPanel(container)
observers.resize(container, { width: 320, height: 200 })
expect(panel.layout()).toBe('compact')◈ Interfaces
Window is expected.Properties
postMessage:MockFnRecords every message posted to this window, and delivers it when the window is linked.readonly origin:stringThe origin this window's own documents run in, compared against a post's target origin.onabort:( this: GlobalEventHandlers, ev: UIEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/abort_event)onanimationcancel:( this: GlobalEventHandlers, ev: AnimationEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/animationcancel_event)onanimationend:( this: GlobalEventHandlers, ev: AnimationEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/animationend_event)onanimationiteration:( this: GlobalEventHandlers, ev: AnimationEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/animationiteration_event)onanimationstart:( this: GlobalEventHandlers, ev: AnimationEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/animationstart_event)onauxclick:( this: GlobalEventHandlers, ev: PointerEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/auxclick_event)onbeforeinput:( this: GlobalEventHandlers, ev: InputEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/beforeinput_event)onbeforematch:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/beforematch_event)onbeforetoggle:( this: GlobalEventHandlers, ev: ToggleEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/beforetoggle_event)onblur:( this: GlobalEventHandlers, ev: FocusEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/blur_event)oncancel:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLDialogElement/cancel_event)oncanplay:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/canplay_event)oncanplaythrough:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/canplaythrough_event)onchange:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/change_event)onclick:( this: GlobalEventHandlers, ev: PointerEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/click_event)onclose:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLDialogElement/close_event)oncontextlost:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLCanvasElement/contextlost_event)oncontextrestored:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLCanvasElement/contextrestored_event)oncopy:( this: GlobalEventHandlers, ev: ClipboardEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/copy_event)oncuechange:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTrackElement/cuechange_event)oncut:( this: GlobalEventHandlers, ev: ClipboardEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/cut_event)ondblclick:( this: GlobalEventHandlers, ev: MouseEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/dblclick_event)ondrag:( this: GlobalEventHandlers, ev: DragEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/drag_event)ondragend:( this: GlobalEventHandlers, ev: DragEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/dragend_event)ondragenter:( this: GlobalEventHandlers, ev: DragEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/dragenter_event)ondragleave:( this: GlobalEventHandlers, ev: DragEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/dragleave_event)ondragover:( this: GlobalEventHandlers, ev: DragEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/dragover_event)ondragstart:( this: GlobalEventHandlers, ev: DragEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/dragstart_event)ondrop:( this: GlobalEventHandlers, ev: DragEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/drop_event)ondurationchange:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/durationchange_event)onemptied:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/emptied_event)onended:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/ended_event)onerror:OnErrorEventHandlerNonNull[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/error_event)onfocus:( this: GlobalEventHandlers, ev: FocusEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/focus_event)onformdata:( this: GlobalEventHandlers, ev: FormDataEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLFormElement/formdata_event)ongotpointercapture:( this: GlobalEventHandlers, ev: PointerEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/gotpointercapture_event)oninput:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/input_event)oninvalid:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/invalid_event)onkeydown:( this: GlobalEventHandlers, ev: KeyboardEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/keydown_event)onkeyup:( this: GlobalEventHandlers, ev: KeyboardEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/keyup_event)onload:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/load_event)onloadeddata:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/loadeddata_event)onloadedmetadata:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/loadedmetadata_event)onloadstart:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/loadstart_event)onlostpointercapture:( this: GlobalEventHandlers, ev: PointerEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/lostpointercapture_event)onmousedown:( this: GlobalEventHandlers, ev: MouseEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/mousedown_event)onmouseenter:( this: GlobalEventHandlers, ev: MouseEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/mouseenter_event)onmouseleave:( this: GlobalEventHandlers, ev: MouseEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/mouseleave_event)onmousemove:( this: GlobalEventHandlers, ev: MouseEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/mousemove_event)onmouseout:( this: GlobalEventHandlers, ev: MouseEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/mouseout_event)onmouseover:( this: GlobalEventHandlers, ev: MouseEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/mouseover_event)onmouseup:( this: GlobalEventHandlers, ev: MouseEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/mouseup_event)onpaste:( this: GlobalEventHandlers, ev: ClipboardEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/paste_event)onpause:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/pause_event)onplay:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/play_event)onplaying:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/playing_event)onpointercancel:( this: GlobalEventHandlers, ev: PointerEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/pointercancel_event)onpointerdown:( this: GlobalEventHandlers, ev: PointerEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/pointerdown_event)onpointerenter:( this: GlobalEventHandlers, ev: PointerEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/pointerenter_event)onpointerleave:( this: GlobalEventHandlers, ev: PointerEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/pointerleave_event)onpointermove:( this: GlobalEventHandlers, ev: PointerEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/pointermove_event)onpointerout:( this: GlobalEventHandlers, ev: PointerEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/pointerout_event)onpointerover:( this: GlobalEventHandlers, ev: PointerEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/pointerover_event)onpointerrawupdate:( this: GlobalEventHandlers, ev: Event) => anyAvailable only in secure contexts. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/pointerrawupdate_event)
onpointerup:( this: GlobalEventHandlers, ev: PointerEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/pointerup_event)onprogress:( this: GlobalEventHandlers, ev: ProgressEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/progress_event)onratechange:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/ratechange_event)onreset:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLFormElement/reset_event)onresize:( this: GlobalEventHandlers, ev: UIEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement/resize_event)onscroll:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/scroll_event)onscrollend:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/scrollend_event)onsecuritypolicyviolation:( this: GlobalEventHandlers, ev: SecurityPolicyViolationEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/securitypolicyviolation_event)onseeked:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/seeked_event)onseeking:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/seeking_event)onselect:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/select_event)onselectionchange:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/selectionchange_event)onselectstart:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Node/selectstart_event)onslotchange:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLSlotElement/slotchange_event)onstalled:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/stalled_event)onsubmit:( this: GlobalEventHandlers, ev: SubmitEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLFormElement/submit_event)onsuspend:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/suspend_event)ontimeupdate:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/timeupdate_event)ontoggle:( this: GlobalEventHandlers, ev: ToggleEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/toggle_event)ontouchcancel?:( this: GlobalEventHandlers, ev: TouchEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/touchcancel_event)ontouchend?:( this: GlobalEventHandlers, ev: TouchEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/touchend_event)ontouchmove?:( this: GlobalEventHandlers, ev: TouchEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/touchmove_event)ontouchstart?:( this: GlobalEventHandlers, ev: TouchEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/touchstart_event)ontransitioncancel:( this: GlobalEventHandlers, ev: TransitionEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/transitioncancel_event)ontransitionend:( this: GlobalEventHandlers, ev: TransitionEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/transitionend_event)ontransitionrun:( this: GlobalEventHandlers, ev: TransitionEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/transitionrun_event)ontransitionstart:( this: GlobalEventHandlers, ev: TransitionEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/transitionstart_event)onvolumechange:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/volumechange_event)onwaiting:( this: GlobalEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMediaElement/waiting_event)onwheel:( this: GlobalEventHandlers, ev: WheelEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/wheel_event)readonly closed:booleanThe Window.closed read-only property indicates whether the referenced window is closed or not. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/closed)
readonly customElements:CustomElementRegistryThe customElements read-only property of the Window interface returns a reference to the CustomElementRegistry object, which can be used to register new custom elements and get information about previously registered custom elements. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/customElements)
readonly devicePixelRatio:numberThe devicePixelRatio of Window interface returns the ratio of the resolution in _physical pixels_ to the resolution in _CSS pixels_ for the current display device. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/devicePixelRatio)
readonly document:Documentwindow.document returns a reference to the document contained in the window. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/document)
readonly event:EventThe read-only Window property event returns the Event which is currently being handled by the site's code.readonly external:ExternalThe external property of the Window API returns an instance of the External interface, which was intended to contain functions related to adding external search providers to the browser.readonly frameElement:ElementThe Window.frameElement property returns the element (such as iframe or object) in which the window is embedded. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/frameElement)
readonly frames:WindowReturns the window itself, which is an array-like object, listing the direct sub-frames of the current window. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/frames)
readonly history:HistoryThe Window.history read-only property returns a reference to the History object, which provides an interface for manipulating the browser _session history_ (pages visited in the tab or frame that the current page is loaded in). [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/history)
readonly innerHeight:numberThe read-only innerHeight property of the including the height of the horizontal scroll bar, if present. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/innerHeight)
readonly innerWidth:numberThe read-only Window property innerWidth returns the interior width of the window in pixels (that is, the width of the window's layout viewport). [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/innerWidth)
readonly length:numberReturns the number of frames (either frame or A number. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/length)
get set location:LocationThe Window.location read-only property returns a Location object with information about the current location of the document. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/location)
readonly locationbar:BarPropReturns the locationbar object. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/locationbar)
name:stringThe Window.name property gets/sets the name of the window's browsing context. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/name)
ondevicemotion:( this: Window, ev: DeviceMotionEvent) => anyAvailable only in secure contexts. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/devicemotion_event)
ondeviceorientation:( this: Window, ev: DeviceOrientationEvent) => anyAvailable only in secure contexts. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/deviceorientation_event)
ondeviceorientationabsolute:( this: Window, ev: DeviceOrientationEvent) => anyAvailable only in secure contexts. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/deviceorientationabsolute_event)
opener:anyThe Window interface's opener property returns a reference to the window that opened the window, either with Window.open, or by navigating a link with a target attribute. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/opener)
readonly orientation:numberReturns the orientation in degrees (in 90-degree increments) of the viewport relative to the device's natural orientation.readonly originAgentCluster:booleanThe originAgentCluster read-only property of the Window interface returns true if this window belongs to an _origin-keyed agent cluster_: this means that the operating system has provided dedicated resources (for example an operating system process) to this window's origin that are not shared with windows from other origins. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/originAgentCluster)
readonly outerHeight:numberThe Window.outerHeight read-only property returns the height in pixels of the whole browser window, including any sidebar, window chrome, and window-resizing borders/handles. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/outerHeight)
readonly outerWidth:numberWindow.outerWidth read-only property returns the width of the outside of the browser window. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/outerWidth)
readonly pageXOffset:number[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/scrollX)readonly pageYOffset:number[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/scrollY)readonly parent:WindowThe Window.parent property is a reference to the parent of the current window or subframe. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/parent)
readonly personalbar:BarPropReturns the personalbar object. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/personalbar)
readonly screen:ScreenThe Window property screen returns a reference to the screen object associated with the window. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/screen)
readonly screenLeft:numberThe Window.screenLeft read-only property returns the horizontal distance, in CSS pixels, from the left border of the user's browser viewport to the left side of the screen. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/screenLeft)
readonly screenTop:numberThe Window.screenTop read-only property returns the vertical distance, in CSS pixels, from the top border of the user's browser viewport to the top side of the screen. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/screenTop)
readonly screenX:numberThe Window.screenX read-only property returns the horizontal distance, in CSS pixels, of the left border of the user's browser viewport to the left side of the screen. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/screenX)
readonly screenY:numberThe Window.screenY read-only property returns the vertical distance, in CSS pixels, of the top border of the user's browser viewport to the top edge of the screen. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/screenY)
readonly scrollX:numberThe read-only scrollX property of the Window interface returns the number of pixels by which the document is currently scrolled horizontally. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/scrollX)
readonly scrollY:numberThe read-only scrollY property of the Window interface returns the number of pixels by which the document is currently scrolled vertically. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/scrollY)
readonly scrollbars:BarPropReturns the scrollbars object. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/scrollbars)
readonly self:Window & unknownThe Window.self read-only property returns the window itself, as a WindowProxy. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/self)
readonly speechSynthesis:SpeechSynthesisThe speechSynthesis read-only property of the Window object returns a SpeechSynthesis object, which is the entry point into using Web Speech API speech synthesis functionality. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/speechSynthesis)
readonly statusbar:BarPropReturns the statusbar object. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/statusbar)
readonly toolbar:BarPropReturns the toolbar object. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/toolbar)
readonly top:WindowReturns a reference to the topmost window in the window hierarchy. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/top)
readonly visualViewport:VisualViewportThe visualViewport read-only property of the Window interface returns a VisualViewport object representing the visual viewport for a given window, or null if current document is not fully active. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/visualViewport)
readonly window:Window & unknownThe window property of a Window object points to the window object itself. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/window)
onafterprint:( this: WindowEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/afterprint_event)onbeforeprint:( this: WindowEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/beforeprint_event)onbeforeunload:( this: WindowEventHandlers, ev: BeforeUnloadEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/beforeunload_event)ongamepadconnected:( this: WindowEventHandlers, ev: GamepadEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/gamepadconnected_event)ongamepaddisconnected:( this: WindowEventHandlers, ev: GamepadEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/gamepaddisconnected_event)onhashchange:( this: WindowEventHandlers, ev: HashChangeEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/hashchange_event)onlanguagechange:( this: WindowEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/languagechange_event)onmessage:( this: WindowEventHandlers, ev: MessageEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/message_event)onmessageerror:( this: WindowEventHandlers, ev: MessageEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/messageerror_event)onoffline:( this: WindowEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/offline_event)ononline:( this: WindowEventHandlers, ev: Event) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/online_event)onpagehide:( this: WindowEventHandlers, ev: PageTransitionEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/pagehide_event)onpagereveal:( this: WindowEventHandlers, ev: PageRevealEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/pagereveal_event)onpageshow:( this: WindowEventHandlers, ev: PageTransitionEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/pageshow_event)onpageswap:( this: WindowEventHandlers, ev: PageSwapEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/pageswap_event)onpopstate:( this: WindowEventHandlers, ev: PopStateEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/popstate_event)onrejectionhandled:( this: WindowEventHandlers, ev: PromiseRejectionEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/rejectionhandled_event)onstorage:( this: WindowEventHandlers, ev: StorageEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/storage_event)onunhandledrejection:( this: WindowEventHandlers, ev: PromiseRejectionEvent) => any[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/unhandledrejection_event)readonly localStorage:Storage[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/localStorage)readonly caches:CacheStorageAvailable only in secure contexts. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/caches)
readonly crossOriginIsolated:boolean[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/crossOriginIsolated)readonly indexedDB:IDBFactory[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/indexedDB)readonly isSecureContext:boolean[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/isSecureContext)readonly performance:Performance[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/performance)Methods
atob( data: string): stringParameters
| Name | Type | Description |
|---|---|---|
§data | string |
atob( data: string): stringParameters
| Name | Type | Description |
|---|---|---|
§data | string |
blur( ): voidWindow.blur() method does nothing.btoa( data: string): stringParameters
| Name | Type | Description |
|---|---|---|
§data | string |
btoa( data: string): stringParameters
| Name | Type | Description |
|---|---|---|
§data | string |
cancelAnimationFrame( handle: number): voidParameters
| Name | Type | Description |
|---|---|---|
§handle | number |
cancelAnimationFrame( handle: number): voidParameters
| Name | Type | Description |
|---|---|---|
§handle | number |
captureEvents( ): voidWindow.captureEvents() method does nothing.clearInterval( id: number): voidParameters
| Name | Type | Description |
|---|---|---|
§id | number |
clearInterval( id: number): voidParameters
| Name | Type | Description |
|---|---|---|
§id | number |
clearTimeout( id: number): voidParameters
| Name | Type | Description |
|---|---|---|
§id | number |
clearTimeout( id: number): voidParameters
| Name | Type | Description |
|---|---|---|
§id | number |
close( ): voidWindow.close() method closes the current window, or the window on which it was called. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/close)
confirm( message?: string): booleanwindow.confirm() instructs the browser to display a dialog with an optional message, and to wait until the user either confirms or cancels the dialog. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/confirm)
Parameters
| Name | Type | Description |
|---|---|---|
§message? | string |
createImageBitmap( image: ImageBitmapSource, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise< ImageBitmap>createImageBitmap( image: ImageBitmapSource, options?: ImageBitmapOptions): Promise< ImageBitmap>dispatchEvent() method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent)
dispatchEvent( event: Event): booleandispatchEvent() method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent)
focus( ): void[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/focus)
getComputedStyle( elt: Element, pseudoElt?: string): CSSStyleDeclarationWindow.getComputedStyle() method returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/getComputedStyle)
getSelection( ): SelectiongetSelection() method of the Window interface returns the Selection object associated with the window's document, representing the range of text selected by the user or the current position of the caret. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/getSelection)
matchMedia( query: string): MediaQueryListmatchMedia() method returns a new MediaQueryList object that can then be used to determine if the document matches the media query string, as well as to monitor the document to detect when it matches (or stops matching) that media query. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/matchMedia)
Parameters
| Name | Type | Description |
|---|---|---|
§query | string |
messageListenerCount( ): numbermessage listeners are registered.open() method of the Window interface loads a specified resource into a new or existing browsing context (that is, a tab, a window, or an iframe) under a specified name. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/open)
posted( ): unknown[ ]print( ): void[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/print)
prompt( message?: string, _default?: string): stringwindow.prompt() instructs the browser to display a dialog with an optional message prompting the user to input some text, and to wait until the user either submits the text or cancels the dialog. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/prompt)
queueMicrotask( callback: VoidFunction): voidParameters
| Name | Type | Description |
|---|---|---|
§callback | VoidFunction |
queueMicrotask( callback: VoidFunction): voidParameters
| Name | Type | Description |
|---|---|---|
§callback | VoidFunction |
receive( data: unknown, from?: MessageSender): voidmessage event to this window's listeners now, as if another window had posted it.Parameters
| Name | Type | Description |
|---|---|---|
§data | unknown | |
§from? | MessageSender |
releaseEvents( ): voidreportError( e: any): voidParameters
| Name | Type | Description |
|---|---|---|
§e | any |
reportError( e: any): voidParameters
| Name | Type | Description |
|---|---|---|
§e | any |
requestAnimationFrame( callback: FrameRequestCallback): numberParameters
| Name | Type | Description |
|---|---|---|
§callback | FrameRequestCallback |
requestAnimationFrame( callback: FrameRequestCallback): numberParameters
| Name | Type | Description |
|---|---|---|
§callback | FrameRequestCallback |
requestIdleCallback( callback: IdleRequestCallback, options?: IdleRequestOptions): numberwindow.requestIdleCallback() method queues a function to be called during a browser's idle periods. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/requestIdleCallback)
setInterval( handler: TimerHandler, timeout?: number, ...arguments: any[ ]): numbersetTimeout( handler: TimerHandler, timeout?: number, ...arguments: any[ ]): numberstop( ): voidwindow.stop() stops further resource loading in the current browsing context, equivalent to the stop button in the browser. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/stop)
structuredClone< T>( value: T, options?: StructuredSerializeOptions): T◆ Types
ResizeObserver that installResizeObserver put on the global.A packed package installed outside the workspace and driven through plain Node child processes, for testing what a consumer installs rather than what the workspace resolves.
ƒ Functions
Nothing of the test process reaches the children: no loader hooks, no path aliases, no hoisted
node_modules. A package that only works through those fails here, the way it would for a consumer. The caller removes the directory; for one a whole suite shares, usePackedConsumer registers the hooks itself.Parameters
| Name | Type | Description |
|---|---|---|
§options | PackedConsumerOptions | The tarball, its peers, the install timeout and the Node binary for the children. |
Returns
PackedConsumerExample
Loading every entry of a packed package
const consumer = createPackedConsumer({ tarball: '/tmp/my-lib-1.0.0.tgz' })
try {
expect(consumer.entries('import').filter((entry) => !entry.ok)).toEqual([])
} finally {
consumer.remove()
}node:test hooks that do it. Call it in a
describe body or at the top of a spec file. The returned handle forwards to the consumer current at the time of each call, so it can be captured once and used from any test or hook. Using it outside a test throws, since nothing is installed then. Functions handed to
run are serialised with toString() and executed in the child, so they can close over nothing from the spec: pass values through args and import the package inside the body.Parameters
| Name | Type | Description |
|---|---|---|
§options | PackedConsumerOptions | The tarball, its peers, the install timeout and the Node binary for the children. |
Returns
PackedConsumerExample
Calling the packed package the way a consumer does
const consumer = usePackedConsumer({ tarball: process.env.MY_LIB_TARBALL })
it('imports every entry under plain Node', () => {
expect(consumer.entries('import').filter((entry) => !entry.ok)).toEqual([])
})
it('hashes through the node entry', () => {
const hash = consumer.run(async () => {
const { createHash } = await import('my-lib/node')
return createHash('abc')
})
expect(hash).toBe('ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad')
})◆ Types
type ModuleKind = "import" | "require"The coverage side of a run: lcov reports merged per file, the threshold gate, the per-file table, and the completeness check for source files no test loaded.
ƒ Functions
Parameters
| Name | Type | Description |
|---|---|---|
§file | FileCoverage | The file's merged counters. |
Returns
MetricTotalsExample
Reducing a file's counters
const file = {
path: 'src/double.ts',
lines: new Map([[1, 5], [2, 4], [3, 0]]),
branches: new Map([['2,0', 4], ['2,1', 0]]),
functions: new Map([['1,double', 5]]),
}
fileTotals(file) // => { lines: { found: 3, hit: 2 }, branches: { found: 2, hit: 1 }, functions: { found: 1, hit: 1 } }The comparison is against the project as a whole, which is what a Jest
global threshold meant.Parameters
| Name | Type | Description |
|---|---|---|
§files | unknown | The merged files. |
§thresholds | CoverageThresholds | The percentages the project requires. |
Returns
string[ ]Example
Judging the merged report against a project's thresholds
const measured = [...mergeLcov(reports).values()]
findThresholdShortfalls(measured, { lines: 99, branches: 96, functions: 97 })
// => ['80.00% line coverage does not meet threshold of 99%', '50.00% branch coverage does not meet threshold of 96%']
findThresholdShortfalls(measured, undefined) // => [], nothing declared means nothing to missfindUnmeasuredFiles( measured: unknown, projectRoot: string, include: string[ ], exclude: string[ ]): CompletenessReport
Node's coverage only reports files the run actually loaded, so a source file no test imports simply vanishes instead of landing at zero percent. That silently removes the guarantee a full-coverage threshold is supposed to give: a new, wholly untested file would not fail the build. Comparing the report against the include globs restores it.
Parameters
Returns
CompletenessReportExample
Catching a source file no spec imported
const measured = [...mergeLcov(['/repo/coverage/libs/example/lcov.node.info']).values()]
findUnmeasuredFiles(measured, '/repo/libs/example', ['src/**/*.ts'], ['**/*.spec.ts'])
// => { missing: ['src/orphan.ts'], covered: 4 }A file appears more than once whenever a module was evaluated more than once: after
jest.resetModules a later import re-runs the module body, and V8 measures each evaluation as a script of its own. Treating those as separate files counts every line of the module once per evaluation while crediting only the evaluation that ran it, which drags the percentages down in proportion to how often a suite reset. Combining them is what Jest's provider did implicitly, by accumulating into counters keyed by file rather than by script. Reports from different environments merge the same way, so a file exercised by one environment and merely imported by another is judged on both.
Anything a
node:coverage ignore comment covers is dropped rather than measured. Node omits an ignored line from the report but still writes out the branches and functions sitting on it, marked untaken, while counting them as covered in its own totals. Dropping them is both what makes the two agree and what istanbul ignore used to mean.Parameters
| Name | Type | Description |
|---|---|---|
§lcovPaths | unknown | Paths to the emitted lcov files. |
Returns
Map< string, FileCoverage>Example
Combining every environment's report into one entry per file
const files = mergeLcov(['/repo/coverage/libs/example/lcov.node.info', '/repo/coverage/libs/example/lcov.browser.info'])
files.get('src/double.ts')?.lines // => Map { 1 => 5, 2 => 4, 3 => 0 }, each count summed across records and reportsParameters
| Name | Type | Description |
|---|---|---|
§files | Iterable< | The merged files. |
Returns
MetricTotalsExample
Adding up a whole report
overallTotals(mergeLcov(reports).values()).lines // => { found: 5, hit: 4 }, the sum over every fileA metric with nothing to measure is complete, which is what Jest reported for a file holding no branches at all.
Returns
numberExample
Rendering a metric as a percentage
percentOf({ found: 4, hit: 3 }) // => 75
percentOf({ found: 0, hit: 0 }) // => 100, nothing to measure counts as completeParameters
| Name | Type | Description |
|---|---|---|
§files | unknown | The merged files, in any order. |
Returns
string[ ]Example
Printing the table a run ends with
console.log(renderCoverageTable([...mergeLcov(reports).values()]).join('\n'))
// file | line % | branch % | funcs % | uncovered lines
// -------------------------------------------------------------
// src/double.ts | 66.67 | 50.00 | 100.00 | 3
// src/other.ts | 100.00 | 100.00 | 100.00 |
// -------------------------------------------------------------
// all files | 80.00 | 50.00 | 100.00 |
// -------------------------------------------------------------The raw reports are what Node measured, one per environment and one record per evaluation. A consumer reading coverage off disk wants what the gate judged instead: one record per file, with the counts combined. Paths are written as given, so a caller that needs them anchored somewhere other than the project root rebases them first.
Parameters
| Name | Type | Description |
|---|---|---|
§files | Iterable< | The merged files, in any order. |
Returns
stringExample
Writing the merged report back out
const merged = mergeLcov(['coverage/lcov.node.info', 'coverage/lcov.browser.info'])
writeFileSync('coverage/lcov.info', renderLcov(merged.values()))
// one record per file, its counts combined, in the shape a coverage service readsParameters
| Name | Type | Description |
|---|---|---|
§file | FileCoverage | The file's merged counters. |
Returns
string[ ]Example
Collapsing missed lines into ranges
const file = { path: 'src/a.ts', lines: new Map([[1, 1], [5, 0], [6, 0], [9, 0]]), branches: new Map(), functions: new Map() }
uncoveredRanges(file) // => ['5-6', '9']◆ Types
The counters stay as maps rather than totals because merging is the whole point: two records for the same file have to be combined per line, per function, and per branch before any percentage means anything.
The preload that gives a suite a browser-shaped global: a jsdom window copied onto `globalThis` before the suite's own setup modules run.
ƒ Functions
This module is an
--import entry, loaded after the resolution hooks and before a project's own setup files, so a setup file may already assume document exists. pretendToBeVisual matches what the Jest environment this replaces asked for: it is what supplies requestAnimationFrame and makes the document report itself as visible.Example
Starting a spec from a fresh document
installDom()
document.body.append(document.createElement('main'))
document.querySelector('main') // => the element just appended, on a document no earlier spec has touchedTemporary directories that clean up after themselves, and fixture trees written into them from data a spec declares.
ƒ Functions
Use it at module or suite scope with a matching
after, or inside a single test with a finally that removes it. For a directory every test in a suite gets, useTempDir registers the hooks itself.Parameters
| Name | Type | Description |
|---|---|---|
§options | TempDirOptions | Name prefix, parent and initial files.(default: {}) |
Returns
TempDirExample
A directory one test owns
it('reads the manifest', () => {
const dir = createTempDir({ tree: { 'package.json': { name: 'app' } } })
try {
expect(readManifest(dir.path).name).toBe('app')
} finally {
dir.remove()
}
})node:test hooks that do it. Call it in a
describe body or at the top of a spec file. The returned handle reads the directory current at the time of each call, so it can be captured once and used from any test or hook. Reading it outside a test throws, since no directory exists then.Parameters
| Name | Type | Description |
|---|---|---|
§options | UseTempDirOptions | Name prefix, parent, initial files, and whether tests share one directory.(default: {}) |
Returns
TempDirExample
A fresh directory for every test
describe('loadConfig', () => {
const dir = useTempDir({ tree: { 'package.json': {} } })
it('finds a config file beside the manifest', () => {
dir.write('hf.config.json', { strict: true })
expect(loadConfig(dir.path)).toEqual({ strict: true })
})
})Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The directory to write under. |
§relativePath | string | Where the file goes, relative to the root. |
§content | FileContent | What the file holds. |
Returns
stringExample
Writing a manifest as JSON
writeFile(root, 'packages/app/package.json', { name: 'app' })
// => '<root>/packages/app/package.json', holding '{\n "name": "app"\n}\n'Fixtures held as data in a spec, rather than checked in as files, never look like a real manifest or lockfile to a dependency scanner, and a spec states exactly the files it depends on. Every path must stay inside the root.
Parameters
Example
Laying out a small workspace
writeTree(root, {
'package.json': { name: 'workspace', workspaces: ['packages/*'] },
'packages/app/package.json': { name: 'app' },
'packages/app/src/index.ts': 'export const ready = true\n',
})◈ Interfaces
useTempDir creates and removes its directory.Properties
scope?:"each" | "all"each gives every test a fresh directory; all shares one across the suite. Defaults to each.◆ Types
type FileContent = string | Uint8Array | object/, which are created as needed.type FileTree = Record< string, FileContent>The preload that makes a Jest-style spec loadable by Node's test runner: path aliases, extensionless specifiers, `moduleNameMapper` redirects and `jest.mock` replacements.
ƒ Functions
moduleNameMapper redirects, extensionless TypeScript specifiers, and the module generation that backs jest.resetModules. Node resolves none of these itself. This module is the
--import entry, so it runs before any test code and imports its own dependencies by explicit path: the hooks it is about to install are not available to it yet.Example
Installing the hooks for a hand-run `node --test`
HF_TEST_WORKSPACE_ROOT=/repo node --import @hyperfrontend/testing/hooks --test src/double.spec.tsStand-ins for a process's terminal, standard streams and child processes, for testing command-line tools and interactive prompts, and a Windows-safe way to start npm.
ƒ Functions
console writes through the same streams, so its output is captured too. The takeover is a spy, so jest.restoreAllMocks and the runner's restoreMocks option end it as well as restore. The test runner's own result messages, which share stdout with the code under test, are recognised and passed through, so a capture held across an await never drops a test from the report.Parameters
| Name | Type | Description |
|---|---|---|
§options | CaptureStdioOptions | Which streams to capture, and whether they still print.(default: {}) |
Returns
CapturedStdioExample
Asserting on a warning without printing it
const stdio = captureStdio()
build({ strict: false })
stdio.restore()
expect(stdio.stderr()).toContain('strict mode is off')Parameters
| Name | Type | Description |
|---|---|---|
§signal | StopSignal | The signal sent. |
§platform | Platform | The platform the child runs on, this one by default.(default: process.platform) |
Returns
ChildExitsendSignal result with.Example
The exit a clean shutdown reports on the running platform
cleanSignalExit('SIGINT') // => { code: 0, signal: null } on Linux and macOS, { code: null, signal: 'SIGINT' } on WindowsWrites complete synchronously, so
text() reflects a write as soon as it returns. As a terminal, the stream reports a size and a colour depth, and resize emits the event a terminal emits when its window changes.Parameters
| Name | Type | Description |
|---|---|---|
§options | CapturedOutputOptions | Whether it is a terminal, and its size and colour depth.(default: {}) |
Returns
CapturedOutputExample
Reading what a command printed
const stderr = createCapturedOutput()
const code = await runCli({ argv: ['--bad'], stderr })
expect({ code, message: stderr.text() }).toEqual({ code: 1, message: 'unknown option --bad\n' })spawn to return, whose output, exit and failure the test controls.Parameters
| Name | Type | Description |
|---|---|---|
§options | FakeChildProcessOptions | The process identifier, when a test asserts on it.(default: {}) |
Returns
FakeChildProcessExample
Returning a scripted child from a mocked spawn
jest.mock('node:child_process', () => ({ spawn: jest.fn() }))
it('reports what the worker printed', async () => {
const child = createFakeChildProcess()
jest.mocked(spawn).mockReturnValue(child as never)
const result = runWorker()
child.writeStdout('{"ok":true}\n')
child.exit(0)
expect(await result).toEqual({ ok: true })
})Keys are written into the stream one per turn of the event loop, so a prompt's read loop handles each key, and re-renders, before the next arrives. Keys sent before anything listens are buffered rather than lost. Calls queue behind one another, so two
sendKeys calls without an await between them still arrive in order.Returns
TtyInputExample
Answering a text prompt
const input = createTtyInput()
const output = createCapturedOutput({ tty: true })
const answer = text({ message: 'Name?', input, output })
await input.sendKeys('a', 'd', 'a', Keys.Enter)
expect(await answer).toBe('ada')cmd.exe reads before handing it to a .cmd shim: an argument holding anything but word characters and - . / : = @ + \ is wrapped in double quotes, a trailing run of backslashes is doubled so it does not escape the closing quote, and every character cmd.exe interprets, the quotes included, is escaped with ^. The program receives the argument as written.Parameters
| Name | Type | Description |
|---|---|---|
§argument | string | One argument of the command |
Returns
stringExample
Quoting a path with a space and an ampersand
quoteForCmd('--save-dev') // => '--save-dev'
quoteForCmd('C:\\Tom & Jerry\\lib.tgz') // => '^"C:\\Tom^ ^&^ Jerry\\lib.tgz^"'Parameters
| Name | Type | Description |
|---|---|---|
§stream | Readable | A stream holding data nothing has consumed, such as a PassThrough handed to code that wrote to it. |
Returns
stringExample
Reading what a command wrote to a plain stream
const stdout = new PassThrough()
printSummary(stdout)
expect(readAll(stdout)).toBe('3 packages\n')Parameters
| Name | Type | Description |
|---|---|---|
§child | SignalTarget | The child, as spawn returned it or a stand-in for it. |
§signal | StopSignal | The signal to send. |
Example
Stopping a server the test started
const child = spawn(process.execPath, ['server.js'], { stdio: ['ignore', 'pipe', 'inherit'] })
await once(child.stdout, 'data')
expect(await sendSignal(child, 'SIGINT')).toEqual(cleanSignalExit('SIGINT'))npm, npx, pnpm, yarn or any other command that is a .cmd shim on Windows. Node refuses to start a .cmd file without a shell, and with one it joins an argument array unescaped and prints DEP0190, so on Windows the arguments are quoted for cmd.exe and joined into one command line passed with no array. Everywhere else the command starts directly with its arguments as given.Parameters
Returns
ShimCommandshell option to spawn it withExample
Packing a package on every platform
import { execFileSync } from 'node:child_process'
const npm = shimCommand('npm', ['pack', '--json'])
execFileSync(npm.file, npm.args, { cwd: packageDir, shell: npm.shell })
// on Windows npm.file is 'npm pack --json', npm.args is [] and npm.shell is truespawnSync returns with encoding: 'utf8', for a mocked spawnSync to hand back.Parameters
| Name | Type | Description |
|---|---|---|
§options | SpawnSyncResultOptions | The fields that differ from a clean exit with no output.(default: {}) |
Returns
SpawnSyncReturns< string>Example
Scripting a failed command
jest.mocked(spawnSync).mockReturnValue(spawnSyncResult({ status: 1, stderr: 'not signed' }))
expect(() => verifySignature('app')).toThrow('not signed')◈ Interfaces
Properties
writable:booleanIs true if it is safe to call writable.write(), which means the stream has not been destroyed, errored, or ended.readonly writableAborted:booleanReturns whether the stream was destroyed or errored before emitting 'finish'.readonly writableEnded:booleanIs true after writable.end() has been called. This property does not indicate whether the data has been flushed, for this use writable.writableFinished instead.readonly writableHighWaterMark:numberReturn the value of highWaterMark passed when creating this Writable.readonly writableLength:numberThis property contains the number of bytes (or objects) in the queue ready to be written. The value provides introspection data regarding the status of the highWaterMark.readonly writableCorked:numberNumber of times writable.uncork() needs to be called in order to fully uncork the stream.readonly writableNeedDrain:booleanIs true if the stream's buffer has been full and stream will emit 'drain'.Methods
_write( chunk: any, encoding: BufferEncoding, callback: ( error?: Error) => void): voidParameters
| Name | Type | Description |
|---|---|---|
§chunk | any | |
§encoding | BufferEncoding | |
§callback | ( |
_writev( chunks: { chunk: any; encoding: BufferEncoding }[ ], callback: ( error?: Error) => void): voidParameters
| Name | Type | Description |
|---|---|---|
§chunks | { chunk: any; encoding: BufferEncoding }[ | |
§callback | ( |
Symbol.for('nodejs.rejection') method is called in case a promise rejection happens when emitting an event and captureRejections is enabled on the emitter. It is possible to use events.captureRejectionSymbol in place of Symbol.for('nodejs.rejection'). ``
js import { EventEmitter, captureRejectionSymbol } from 'node:events';
class MyClass extends EventEmitter { constructor() { super({ captureRejections: true }); }
[captureRejectionSymbol](err, event, ...args) { console.log('rejection happened for', event, 'with', err, ...args); this.destroy(err); }
destroy(err) { // Tear the resource down here. } } ``addListener< E>( eventName: E, listener: ( args: indexedAccess) => void): thisemitter.on(eventName, listener).clear( ): voidcork( ): voidwritable.cork() method forces all written data to be buffered in memory. The buffered data will be flushed when either the uncork or end methods are called. The primary intent of
writable.cork() is to accommodate a situation in which several small chunks are written to the stream in rapid succession. Instead of immediately forwarding them to the underlying destination, writable.cork() buffers all the chunks until writable.uncork() is called, which will pass them all to writable._writev(), if present. This prevents a head-of-line blocking situation where data is being buffered while waiting for the first small chunk to be processed. However, use of writable.cork() without implementing writable._writev() may have an adverse effect on throughput. See also:
writable.uncork(), writable._writev().'error' event, and emit a 'close' event (unless emitClose is set to false). After this call, the writable stream has ended and subsequent calls to write() or end() will result in an ERR_STREAM_DESTROYED error. This is a destructive and immediate way to destroy a stream. Previous calls to write() may not have drained, and may trigger an ERR_STREAM_DESTROYED error. Use end() instead of destroy if data should flush before close, or wait for the 'drain' event before destroying the stream. Once
destroy() has been called any further calls will be a no-op and no further errors except from _destroy() may be emitted as 'error'. Implementors should not override this method, but instead implement
writable._destroy().emit< E>( eventName: E, ...args: indexedAccess): booleaneventName, in the order they were registered, passing the supplied arguments to each. Returns
true if the event had listeners, false otherwise. ``
js import { EventEmitter } from 'node:events'; const myEmitter = new EventEmitter();
// First listener myEmitter.on('event', function firstListener() { console.log('Helloooo! first listener'); }); // Second listener myEmitter.on('event', function secondListener(arg1, arg2) { console.log(event with parameters ${arg1}, ${arg2} in second listener); }); // Third listener myEmitter.on('event', function thirdListener(...args) { const parameters = args.join(', '); console.log(event with parameters ${parameters} in third listener); });
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints: // [ // [Function: firstListener], // [Function: secondListener], // [Function: thirdListener] // ] // Helloooo! first listener // event with parameters 1, 2 in second listener // event with parameters 1, 2, 3, 4, 5 in third listener ``end( cb?: ( ) => void): thiswritable.end() method signals that no more data will be written to the Writable. The optional chunk and encoding arguments allow one final additional chunk of data to be written immediately before closing the stream. Calling the write method after calling end will raise an error.
``
js // Write 'hello, ' and then end with 'world!'. import fs from 'node:fs'; const file = fs.createWriteStream('example.txt'); file.write('hello, '); file.end('world!'); // Writing more now is not allowed! ``Parameters
| Name | Type | Description |
|---|---|---|
§cb? | ( | Callback for when the stream is finished. |
end( chunk: any, cb?: ( ) => void): thisend( chunk: any, encoding: BufferEncoding, cb?: ( ) => void): thisParameters
| Name | Type | Description |
|---|---|---|
§chunk | any | Optional data to write. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams, chunk may be any JavaScript value other than null. |
§encoding | BufferEncoding | The encoding if chunk is a string |
§cb? | ( | Callback for when the stream is finished. |
eventNames( ): ( string | symbol)[ ]``
js import { EventEmitter } from 'node:events';
const myEE = new EventEmitter(); myEE.on('foo', () => {}); myEE.on('bar', () => {});
const sym = Symbol('symbol'); myEE.on(sym, () => {});
console.log(myEE.eventNames()); // Prints: [ 'foo', 'bar', Symbol(symbol) ] ``getColorDepth( ): numberWriteStream does.getMaxListeners( ): numberEventEmitter which is either set by emitter.setMaxListeners(n) or defaults to events.defaultMaxListeners.listenerCount< E>( eventName: E, listener?: ( args: indexedAccess) => void): numbereventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.listeners< E>( eventName: E): ( args: indexedAccess) => void[ ]eventName. ``
js server.on('connection', (stream) => { console.log('someone connected!'); }); console.log(util.inspect(server.listeners('connection'))); // Prints: [ [Function] ] ``Parameters
| Name | Type | Description |
|---|---|---|
§eventName | E |
listeners( eventName: string | symbol): ( args: any[ ]) => void[ ]Parameters
| Name | Type | Description |
|---|---|---|
§eventName | string | symbol |
off< E>( eventName: E, listener: ( args: indexedAccess) => void): thisemitter.removeListener().on< E>( eventName: E, listener: ( args: indexedAccess) => void): thislistener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times. ``
js server.on('connection', (stream) => { console.log('someone connected!'); }); `
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.
`js import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => console.log('a')); myEE.prependListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a ``once< E>( eventName: E, listener: ( args: indexedAccess) => void): thislistener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked. ``
js server.once('connection', (stream) => { console.log('Ah, we have our first user!'); }); `
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.
`js import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.once('foo', () => console.log('a')); myEE.prependOnceListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a ``prependListener< E>( eventName: E, listener: ( args: indexedAccess) => void): thislistener function to the _beginning_ of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times. ``
js server.prependListener('connection', (stream) => { console.log('someone connected!'); }); `
Returns a reference to the EventEmitter`, so that calls can be chained.prependOnceListener< E>( eventName: E, listener: ( args: indexedAccess) => void): thislistener function for the event named eventName to the _beginning_ of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked. ``
js server.prependOnceListener('connection', (stream) => { console.log('Ah, we have our first user!'); }); `
Returns a reference to the EventEmitter`, so that calls can be chained.rawListeners< E>( eventName: E): ( args: indexedAccess) => void[ ]eventName, including any wrappers (such as those created by .once()). ``
js import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); emitter.once('log', () => console.log('log once'));
// Returns a new Array with a function onceWrapper which has a property // listener which contains the original listener bound above const listeners = emitter.rawListeners('log'); const logFnWrapper = listeners[0];
// Logs "log once" to the console and does not unbind the once event logFnWrapper.listener();
// Logs "log once" to the console and removes the listener logFnWrapper();
emitter.on('log', () => console.log('log persistently')); // Will return a new Array with a single function bound by .on() above const newListeners = emitter.rawListeners('log');
// Logs "log persistently" twice newListeners[0](); emitter.emit('log'); ``Parameters
| Name | Type | Description |
|---|---|---|
§eventName | E |
rawListeners( eventName: string | symbol): ( args: any[ ]) => void[ ]Parameters
| Name | Type | Description |
|---|---|---|
§eventName | string | symbol |
removeAllListeners< E>( eventName?: E): thiseventName. It is bad practice to remove listeners added elsewhere in the code, particularly when the
EventEmitter instance was created by some other component or module (e.g. sockets or file streams). Returns a reference to the
EventEmitter, so that calls can be chained.Parameters
| Name | Type | Description |
|---|---|---|
§eventName? | E |
removeAllListeners( eventName?: string | symbol): thisParameters
| Name | Type | Description |
|---|---|---|
§eventName? | string | symbol |
removeListener< E>( eventName: E, listener: ( args: indexedAccess) => void): thislistener from the listener array for the event named eventName. ``
js const callback = (stream) => { console.log('someone connected!'); }; server.on('connection', callback); // ... server.removeListener('connection', callback); `
removeListener() will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified eventName, then removeListener() must be called multiple times to remove each instance.
Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any removeListener() or removeAllListeners() calls _after_ emitting and _before_ the last listener finishes execution will not remove them from emit() in progress. Subsequent events behave as expected.
`js import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter();
const callbackA = () => { console.log('A'); myEmitter.removeListener('event', callbackB); };
const callbackB = () => { console.log('B'); };
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called. // Internal listener array at time of emit [callbackA, callbackB] myEmitter.emit('event'); // Prints: // A // B
// callbackB is now removed. // Internal listener array [callbackA] myEmitter.emit('event'); // Prints: // A `
Because listeners are managed using an internal array, calling this will change the position indexes of any listener registered _after_ the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the emitter.listeners() method will need to be recreated.
When a single function has been added as a handler multiple times for a single event (as in the example below), removeListener() will remove the most recently added instance. In the example the once('ping') listener is removed:
`js import { EventEmitter } from 'node:events'; const ee = new EventEmitter();
function pong() { console.log('pong'); }
ee.on('ping', pong); ee.once('ping', pong); ee.removeListener('ping', pong);
ee.emit('ping'); ee.emit('ping'); `
Returns a reference to the EventEmitter`, so that calls can be chained.setDefaultEncoding( encoding: BufferEncoding): thiswritable.setDefaultEncoding() method sets the default encoding for a Writable stream.Parameters
| Name | Type | Description |
|---|---|---|
§encoding | BufferEncoding | The new default encoding |
setMaxListeners( n: number): thisEventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default that helps finding memory leaks. The emitter.setMaxListeners() method allows the limit to be modified for this specific EventEmitter instance. The value can be set to Infinity (or 0) to indicate an unlimited number of listeners. Returns a reference to the
EventEmitter, so that calls can be chained.Parameters
| Name | Type | Description |
|---|---|---|
§n | number |
text( ): stringuncork( ): voidwritable.uncork() method flushes all data buffered since cork was called. When using
writable.cork() and writable.uncork() to manage the buffering of writes to a stream, defer calls to writable.uncork() using process.nextTick(). Doing so allows batching of all writable.write() calls that occur within a given Node.js event loop phase. ``
js stream.cork(); stream.write('some '); stream.write('data '); process.nextTick(() => stream.uncork()); `
If the writable.cork() method is called multiple times on a stream, the same number of calls to writable.uncork() must be called to flush the buffered data.
`js stream.cork(); stream.write('some '); stream.cork(); stream.write('data '); process.nextTick(() => { stream.uncork(); // The data will not be flushed until uncork() is called a second time. stream.uncork(); }); `
See also: writable.cork()`.writable.write() method writes some data to the stream, and calls the supplied callback once the data has been fully handled. If an error occurs, the callback will be called with the error as its first argument. The callback is called asynchronously and before 'error' is emitted. The return value is
true if the internal buffer is less than the highWaterMark configured when the stream was created after admitting chunk. If false is returned, further attempts to write data to the stream should stop until the 'drain' event is emitted. While a stream is not draining, calls to
write() will buffer chunk, and return false. Once all currently buffered chunks are drained (accepted for delivery by the operating system), the 'drain' event will be emitted. Once write() returns false, do not write more chunks until the 'drain' event is emitted. While calling write() on a stream that is not draining is allowed, Node.js will buffer all written chunks until maximum memory usage occurs, at which point it will abort unconditionally. Even before it aborts, high memory usage will cause poor garbage collector performance and high RSS (which is not typically released back to the system, even after the memory is no longer required). Since TCP sockets may never drain if the remote peer does not read the data, writing a socket that is not draining may lead to a remotely exploitable vulnerability. Writing data while the stream is not draining is particularly problematic for a
Transform, because the Transform streams are paused by default until they are piped or a 'data' or 'readable' event handler is added. If the data to be written can be generated or fetched on demand, it is recommended to encapsulate the logic into a
Readable and use pipe. However, if calling write() is preferred, it is possible to respect backpressure and avoid memory issues using the 'drain' event: ``
js function write(data, cb) { if (!stream.write(data)) { stream.once('drain', cb); } else { process.nextTick(cb); } }
// Wait for cb to be called before doing any other write. write('hello', () => { console.log('Write completed, do more writes now.'); }); `
A Writable stream in object mode will always ignore the encoding` argument.Parameters
| Name | Type | Description |
|---|---|---|
§chunk | any | Optional data to write. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams, chunk may be any JavaScript value other than null. |
§callback? | ( | Callback for when this chunk of data is flushed. |
Returns
booleanfalse if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.write( chunk: any, encoding: BufferEncoding, callback?: ( error: Error) => void): booleanParameters
| Name | Type | Description |
|---|---|---|
§chunk | any | Optional data to write. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams, chunk may be any JavaScript value other than null. |
§encoding | BufferEncoding | The encoding, if chunk is a string. |
§callback? | ( | Callback for when this chunk of data is flushed. |
Returns
booleanfalse if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.Properties
ChildProcess that spawn, fork and exec return, which a test drives by hand.Properties
pid:numberProcess identifier, or undefined as for a child the system never started. Assign undefined to model one.Methods
Symbol.for('nodejs.rejection') method is called in case a promise rejection happens when emitting an event and captureRejections is enabled on the emitter. It is possible to use events.captureRejectionSymbol in place of Symbol.for('nodejs.rejection'). ``
js import { EventEmitter, captureRejectionSymbol } from 'node:events';
class MyClass extends EventEmitter { constructor() { super({ captureRejections: true }); }
[captureRejectionSymbol](err, event, ...args) { console.log('rejection happened for', event, 'with', err, ...args); this.destroy(err); }
destroy(err) { // Tear the resource down here. } } ``emit< E>( eventName: string | symbol, ...args: any[ ]): booleaneventName, in the order they were registered, passing the supplied arguments to each. Returns
true if the event had listeners, false otherwise. ``
js import { EventEmitter } from 'node:events'; const myEmitter = new EventEmitter();
// First listener myEmitter.on('event', function firstListener() { console.log('Helloooo! first listener'); }); // Second listener myEmitter.on('event', function secondListener(arg1, arg2) { console.log(event with parameters ${arg1}, ${arg2} in second listener); }); // Third listener myEmitter.on('event', function thirdListener(...args) { const parameters = args.join(', '); console.log(event with parameters ${parameters} in third listener); });
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints: // [ // [Function: firstListener], // [Function: secondListener], // [Function: thirdListener] // ] // Helloooo! first listener // event with parameters 1, 2 in second listener // event with parameters 1, 2, 3, 4, 5 in third listener ``eventNames( ): ( string | symbol)[ ]``
js import { EventEmitter } from 'node:events';
const myEE = new EventEmitter(); myEE.on('foo', () => {}); myEE.on('bar', () => {});
const sym = Symbol('symbol'); myEE.on(sym, () => {});
console.log(myEE.eventNames()); // Prints: [ 'foo', 'bar', Symbol(symbol) ] ``getMaxListeners( ): numberEventEmitter which is either set by emitter.setMaxListeners(n) or defaults to events.defaultMaxListeners.listenerCount< E>( eventName: string | symbol, listener?: ( args: any[ ]) => void): numbereventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.listeners< E>( eventName: string | symbol): ( args: any[ ]) => void[ ]eventName. ``
js server.on('connection', (stream) => { console.log('someone connected!'); }); console.log(util.inspect(server.listeners('connection'))); // Prints: [ [Function] ] ``Parameters
| Name | Type | Description |
|---|---|---|
§eventName | string | symbol |
on< E>( eventName: string | symbol, listener: ( args: any[ ]) => void): thislistener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times. ``
js server.on('connection', (stream) => { console.log('someone connected!'); }); `
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.
`js import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => console.log('a')); myEE.prependListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a ``once< E>( eventName: string | symbol, listener: ( args: any[ ]) => void): thislistener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked. ``
js server.once('connection', (stream) => { console.log('Ah, we have our first user!'); }); `
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.
`js import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.once('foo', () => console.log('a')); myEE.prependOnceListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a ``prependListener< E>( eventName: string | symbol, listener: ( args: any[ ]) => void): thislistener function to the _beginning_ of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times. ``
js server.prependListener('connection', (stream) => { console.log('someone connected!'); }); `
Returns a reference to the EventEmitter`, so that calls can be chained.prependOnceListener< E>( eventName: string | symbol, listener: ( args: any[ ]) => void): thislistener function for the event named eventName to the _beginning_ of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked. ``
js server.prependOnceListener('connection', (stream) => { console.log('Ah, we have our first user!'); }); `
Returns a reference to the EventEmitter`, so that calls can be chained.rawListeners< E>( eventName: string | symbol): ( args: any[ ]) => void[ ]eventName, including any wrappers (such as those created by .once()). ``
js import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); emitter.once('log', () => console.log('log once'));
// Returns a new Array with a function onceWrapper which has a property // listener which contains the original listener bound above const listeners = emitter.rawListeners('log'); const logFnWrapper = listeners[0];
// Logs "log once" to the console and does not unbind the once event logFnWrapper.listener();
// Logs "log once" to the console and removes the listener logFnWrapper();
emitter.on('log', () => console.log('log persistently')); // Will return a new Array with a single function bound by .on() above const newListeners = emitter.rawListeners('log');
// Logs "log persistently" twice newListeners[0](); emitter.emit('log'); ``Parameters
| Name | Type | Description |
|---|---|---|
§eventName | string | symbol |
removeAllListeners< E>( eventName?: string | symbol): thiseventName. It is bad practice to remove listeners added elsewhere in the code, particularly when the
EventEmitter instance was created by some other component or module (e.g. sockets or file streams). Returns a reference to the
EventEmitter, so that calls can be chained.Parameters
| Name | Type | Description |
|---|---|---|
§eventName? | string | symbol |
removeListener< E>( eventName: string | symbol, listener: ( args: any[ ]) => void): thislistener from the listener array for the event named eventName. ``
js const callback = (stream) => { console.log('someone connected!'); }; server.on('connection', callback); // ... server.removeListener('connection', callback); `
removeListener() will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified eventName, then removeListener() must be called multiple times to remove each instance.
Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any removeListener() or removeAllListeners() calls _after_ emitting and _before_ the last listener finishes execution will not remove them from emit() in progress. Subsequent events behave as expected.
`js import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter();
const callbackA = () => { console.log('A'); myEmitter.removeListener('event', callbackB); };
const callbackB = () => { console.log('B'); };
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called. // Internal listener array at time of emit [callbackA, callbackB] myEmitter.emit('event'); // Prints: // A // B
// callbackB is now removed. // Internal listener array [callbackA] myEmitter.emit('event'); // Prints: // A `
Because listeners are managed using an internal array, calling this will change the position indexes of any listener registered _after_ the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the emitter.listeners() method will need to be recreated.
When a single function has been added as a handler multiple times for a single event (as in the example below), removeListener() will remove the most recently added instance. In the example the once('ping') listener is removed:
`js import { EventEmitter } from 'node:events'; const ee = new EventEmitter();
function pong() { console.log('pong'); }
ee.on('ping', pong); ee.once('ping', pong); ee.removeListener('ping', pong);
ee.emit('ping'); ee.emit('ping'); `
Returns a reference to the EventEmitter`, so that calls can be chained.setMaxListeners( n: number): thisEventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default that helps finding memory leaks. The emitter.setMaxListeners() method allows the limit to be modified for this specific EventEmitter instance. The value can be set to Infinity (or 0) to indicate an unlimited number of listeners. Returns a reference to the
EventEmitter, so that calls can be chained.Parameters
| Name | Type | Description |
|---|---|---|
§n | number |
.cmd shim on Windows: the values to spread into execFileSync, execFile, spawn or spawnSync from node:child_process.Properties
readonly file:stringThe program, or on Windows the whole command line with its arguments quoted for cmd.exe.spawn returns, or a stand-in for it.Properties
Methods
kill( signal: StopSignal): booleanParameters
| Name | Type | Description |
|---|---|---|
§signal | StopSignal |
Properties
readonly readableAborted:booleanReturns whether the stream was destroyed or errored before emitting 'end'.readable:booleanIs true if it is safe to call read, which means the stream has not been destroyed or emitted 'error' or 'end'.readonly readableEncoding:BufferEncodingGetter for the property encoding of a given Readable stream. The encoding property can be set using the setEncoding method.readonly readableEnded:booleanBecomes true when ['end'](https://nodejs.org/docs/latest-v25.x/api/stream.html#event-end) event is emitted.readableFlowing:booleanThis property reflects the current state of a Readable stream as described in the [Three states](https://nodejs.org/docs/latest-v25.x/api/stream.html#three-states) section.readonly readableHighWaterMark:numberReturns the value of highWaterMark passed when creating this Readable.readonly readableLength:numberThis property contains the number of bytes (or objects) in the queue ready to be read. The value provides introspection data regarding the status of the highWaterMark.writable:booleanIs true if it is safe to call writable.write(), which means the stream has not been destroyed, errored, or ended.readonly writableAborted:booleanReturns whether the stream was destroyed or errored before emitting 'finish'.readonly writableEnded:booleanIs true after writable.end() has been called. This property does not indicate whether the data has been flushed, for this use writable.writableFinished instead.readonly writableHighWaterMark:numberReturn the value of highWaterMark passed when creating this Writable.readonly writableLength:numberThis property contains the number of bytes (or objects) in the queue ready to be written. The value provides introspection data regarding the status of the highWaterMark.readonly writableCorked:numberNumber of times writable.uncork() needs to be called in order to fully uncork the stream.readonly writableNeedDrain:booleanIs true if the stream's buffer has been full and stream will emit 'drain'.allowHalfOpen:booleanIf false then the stream will automatically end the writable side when the readable side ends. Set initially by the allowHalfOpen constructor option, which defaults to true. This can be changed manually to change the half-open behavior of an existing
Duplex stream instance, but must be changed before the 'end' event is emitted.Methods
_transform( chunk: any, encoding: BufferEncoding, callback: TransformCallback): voidParameters
| Name | Type | Description |
|---|---|---|
§chunk | any | |
§encoding | BufferEncoding | |
§callback | TransformCallback |
_write( chunk: any, encoding: BufferEncoding, callback: ( error?: Error) => void): voidParameters
| Name | Type | Description |
|---|---|---|
§chunk | any | |
§encoding | BufferEncoding | |
§callback | ( |
_writev( chunks: { chunk: any; encoding: BufferEncoding }[ ], callback: ( error?: Error) => void): voidParameters
| Name | Type | Description |
|---|---|---|
§chunks | { chunk: any; encoding: BufferEncoding }[ | |
§callback | ( |
[asyncIterator]( ): AsyncIterator< any>Returns
AsyncIterator< any>AsyncIterator to fully consume the stream.Symbol.for('nodejs.rejection') method is called in case a promise rejection happens when emitting an event and captureRejections is enabled on the emitter. It is possible to use events.captureRejectionSymbol in place of Symbol.for('nodejs.rejection'). ``
js import { EventEmitter, captureRejectionSymbol } from 'node:events';
class MyClass extends EventEmitter { constructor() { super({ captureRejections: true }); }
[captureRejectionSymbol](err, event, ...args) { console.log('rejection happened for', event, 'with', err, ...args); this.destroy(err); }
destroy(err) { // Tear the resource down here. } } ``addListener< E>( eventName: E, listener: ( args: indexedAccess) => void): thisemitter.on(eventName, listener).compose( stream: WritableStream | WritableStream< any> | TransformStream< any, any> | ( source: any) => void, options?: Abortable): Duplexjs import { Readable } from 'node:stream';
async function* splitToWords(source) { for await (const chunk of source) { const words = String(chunk).split(' ');
for (const word of words) { yield word; } } }
const wordsStream = Readable.from(['text passed through', 'composed stream']).compose(splitToWords); const words = await wordsStream.toArray();
console.log(words); // prints ['text', 'passed', 'through', 'composed', 'stream'] `
readable.compose(s) is equivalent to stream.compose(readable, s).
This method also allows for an AbortSignal to be provided, which will destroy the composed stream when aborted.
See [stream.compose(...streams)`](https://nodejs.org/docs/latest-v25.x/api/stream.html#streamcomposestreams) for more information.Parameters
| Name | Type | Description |
|---|---|---|
§stream | WritableStream | WritableStream< | |
§options? | Abortable |
Returns
Duplexstream.cork( ): voidwritable.cork() method forces all written data to be buffered in memory. The buffered data will be flushed when either the uncork or end methods are called. The primary intent of
writable.cork() is to accommodate a situation in which several small chunks are written to the stream in rapid succession. Instead of immediately forwarding them to the underlying destination, writable.cork() buffers all the chunks until writable.uncork() is called, which will pass them all to writable._writev(), if present. This prevents a head-of-line blocking situation where data is being buffered while waiting for the first small chunk to be processed. However, use of writable.cork() without implementing writable._writev() may have an adverse effect on throughput. See also:
writable.uncork(), writable._writev().'error' event, and emit a 'close' event (unless emitClose is set to false). After this call, the readable stream will release any internal resources and subsequent calls to push() will be ignored. Once
destroy() has been called any further calls will be a no-op and no further errors except from _destroy() may be emitted as 'error'. Implementors should not override this method, but instead implement
readable._destroy().drop( limit: number, options?: Abortable): ReadableReturns
Readableemit< E>( eventName: E, ...args: indexedAccess): booleaneventName, in the order they were registered, passing the supplied arguments to each. Returns
true if the event had listeners, false otherwise. ``
js import { EventEmitter } from 'node:events'; const myEmitter = new EventEmitter();
// First listener myEmitter.on('event', function firstListener() { console.log('Helloooo! first listener'); }); // Second listener myEmitter.on('event', function secondListener(arg1, arg2) { console.log(event with parameters ${arg1}, ${arg2} in second listener); }); // Third listener myEmitter.on('event', function thirdListener(...args) { const parameters = args.join(', '); console.log(event with parameters ${parameters} in third listener); });
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints: // [ // [Function: firstListener], // [Function: secondListener], // [Function: thirdListener] // ] // Helloooo! first listener // event with parameters 1, 2 in second listener // event with parameters 1, 2, 3, 4, 5 in third listener ``end( cb?: ( ) => void): thiswritable.end() method signals that no more data will be written to the Writable. The optional chunk and encoding arguments allow one final additional chunk of data to be written immediately before closing the stream. Calling the write method after calling end will raise an error.
``
js // Write 'hello, ' and then end with 'world!'. import fs from 'node:fs'; const file = fs.createWriteStream('example.txt'); file.write('hello, '); file.end('world!'); // Writing more now is not allowed! ``Parameters
| Name | Type | Description |
|---|---|---|
§cb? | ( | Callback for when the stream is finished. |
end( chunk: any, cb?: ( ) => void): thisend( chunk: any, encoding: BufferEncoding, cb?: ( ) => void): thisParameters
| Name | Type | Description |
|---|---|---|
§chunk | any | Optional data to write. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams, chunk may be any JavaScript value other than null. |
§encoding | BufferEncoding | The encoding if chunk is a string |
§cb? | ( | Callback for when the stream is finished. |
eventNames( ): ( string | symbol)[ ]``
js import { EventEmitter } from 'node:events';
const myEE = new EventEmitter(); myEE.on('foo', () => {}); myEE.on('bar', () => {});
const sym = Symbol('symbol'); myEE.on(sym, () => {});
console.log(myEE.eventNames()); // Prints: [ 'foo', 'bar', Symbol(symbol) ] ``every( fn: ( data: any, options?: Abortable) => boolean | Promise< boolean>, options?: Pick< ReadableOperatorOptions, "concurrency" | "signal">): Promise< boolean>Array.prototype.every and calls fn on each chunk in the stream to check if all awaited return values are truthy value for fn. Once an fn call on a chunk awaited return value is falsy, the stream is destroyed and the promise is fulfilled with false. If all of the fn calls on the chunks return a truthy value, the promise is fulfilled with true.Returns
Promise< boolean>true if fn returned a truthy value for every one of the chunks.filter( fn: ( data: any, options?: Abortable) => boolean | Promise< boolean>, options?: ReadableOperatorOptions): Readableawaited.Returns
Readablefind< T>( fn: ( data: any, options?: Abortable) => unknown, options?: Pick< ReadableOperatorOptions, "concurrency" | "signal">): Promise< T>Array.prototype.find and calls fn on each chunk in the stream to find a chunk with a truthy value for fn. Once an fn call's awaited return value is truthy, the stream is destroyed and the promise is fulfilled with value for which fn returned a truthy value. If all of the fn calls on the chunks return a falsy value, the promise is fulfilled with undefined.Returns
Promise< T>undefined if no element was found.find( fn: ( data: any, options?: Abortable) => boolean | Promise< boolean>, options?: Pick< ReadableOperatorOptions, "concurrency" | "signal">): Promise< any>Array.prototype.find and calls fn on each chunk in the stream to find a chunk with a truthy value for fn. Once an fn call's awaited return value is truthy, the stream is destroyed and the promise is fulfilled with value for which fn returned a truthy value. If all of the fn calls on the chunks return a falsy value, the promise is fulfilled with undefined.Returns
Promise< any>undefined if no element was found.flatMap( fn: ( data: any, options?: Abortable) => any, options?: Pick< ReadableOperatorOptions, "concurrency" | "signal">): ReadableIt is possible to return a stream or another iterable or async iterable from fn and the result streams will be merged (flattened) into the returned stream.
Returns
ReadableforEach( fn: ( data: any, options?: Abortable) => void | Promise< void>, options?: Pick< ReadableOperatorOptions, "concurrency" | "signal">): Promise< void>awaited. This method is different from
for await...of loops in that it can optionally process chunks concurrently. In addition, a forEach iteration can only be stopped by having passed a signal option and aborting the related AbortController while for await...of can be stopped with break or return. In either case the stream will be destroyed. This method is different from listening to the
'data' event in that it uses the readable event in the underlying machinary and can limit the number of concurrent fn calls.Returns
Promise< void>getMaxListeners( ): numberEventEmitter which is either set by emitter.setMaxListeners(n) or defaults to events.defaultMaxListeners.isPaused( ): booleanreadable.isPaused() method returns the current operating state of the Readable. This is used primarily by the mechanism that underlies the readable.pipe() method. In most typical cases, there will be no reason to use this method directly. ``
js const readable = new stream.Readable();
readable.isPaused(); // === false readable.pause(); readable.isPaused(); // === true readable.resume(); readable.isPaused(); // === false ``iterator( options?: ReadableIteratorOptions): AsyncIterator< any>for await...of loop is exited by return, break, or throw, or if the iterator should destroy the stream if the stream emitted an error during iteration.Parameters
| Name | Type | Description |
|---|---|---|
§options? | ReadableIteratorOptions |
listenerCount< E>( eventName: E, listener?: ( args: indexedAccess) => void): numbereventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.listeners< E>( eventName: E): ( args: indexedAccess) => void[ ]eventName. ``
js server.on('connection', (stream) => { console.log('someone connected!'); }); console.log(util.inspect(server.listeners('connection'))); // Prints: [ [Function] ] ``Parameters
| Name | Type | Description |
|---|---|---|
§eventName | E |
listeners( eventName: string | symbol): ( args: any[ ]) => void[ ]Parameters
| Name | Type | Description |
|---|---|---|
§eventName | string | symbol |
map( fn: ( data: any, options?: Abortable) => any, options?: ReadableOperatorOptions): Readableawaited before being passed to the result stream.Returns
Readableoff< E>( eventName: E, listener: ( args: indexedAccess) => void): thisemitter.removeListener().on< E>( eventName: E, listener: ( args: indexedAccess) => void): thislistener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times. ``
js server.on('connection', (stream) => { console.log('someone connected!'); }); `
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.
`js import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.on('foo', () => console.log('a')); myEE.prependListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a ``once< E>( eventName: E, listener: ( args: indexedAccess) => void): thislistener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked. ``
js server.once('connection', (stream) => { console.log('Ah, we have our first user!'); }); `
Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The emitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.
`js import { EventEmitter } from 'node:events'; const myEE = new EventEmitter(); myEE.once('foo', () => console.log('a')); myEE.prependOnceListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a ``pause( ): thisreadable.pause() method will cause a stream in flowing mode to stop emitting 'data' events, switching out of flowing mode. Any data that becomes available will remain in the internal buffer. ``
js const readable = getReadableStreamSomehow(); readable.on('data', (chunk) => { console.log(Received ${chunk.length} bytes of data.); readable.pause(); console.log('There will be no additional data for 1 second.'); setTimeout(() => { console.log('Now data will start flowing again.'); readable.resume(); }, 1000); }); `
The readable.pause() method has no effect if there is a 'readable'` event listener.prependListener< E>( eventName: E, listener: ( args: indexedAccess) => void): thislistener function to the _beginning_ of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times. ``
js server.prependListener('connection', (stream) => { console.log('someone connected!'); }); `
Returns a reference to the EventEmitter`, so that calls can be chained.prependOnceListener< E>( eventName: E, listener: ( args: indexedAccess) => void): thislistener function for the event named eventName to the _beginning_ of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked. ``
js server.prependOnceListener('connection', (stream) => { console.log('Ah, we have our first user!'); }); `
Returns a reference to the EventEmitter`, so that calls can be chained.push( chunk: any, encoding?: BufferEncoding): booleanParameters
| Name | Type | Description |
|---|---|---|
§chunk | any | |
§encoding? | BufferEncoding |
rawListeners< E>( eventName: E): ( args: indexedAccess) => void[ ]eventName, including any wrappers (such as those created by .once()). ``
js import { EventEmitter } from 'node:events'; const emitter = new EventEmitter(); emitter.once('log', () => console.log('log once'));
// Returns a new Array with a function onceWrapper which has a property // listener which contains the original listener bound above const listeners = emitter.rawListeners('log'); const logFnWrapper = listeners[0];
// Logs "log once" to the console and does not unbind the once event logFnWrapper.listener();
// Logs "log once" to the console and removes the listener logFnWrapper();
emitter.on('log', () => console.log('log persistently')); // Will return a new Array with a single function bound by .on() above const newListeners = emitter.rawListeners('log');
// Logs "log persistently" twice newListeners[0](); emitter.emit('log'); ``Parameters
| Name | Type | Description |
|---|---|---|
§eventName | E |
rawListeners( eventName: string | symbol): ( args: any[ ]) => void[ ]Parameters
| Name | Type | Description |
|---|---|---|
§eventName | string | symbol |
read( size?: number): anyreadable.read() method reads data out of the internal buffer and returns it. If no data is available to be read, null is returned. By default, the data is returned as a Buffer object unless an encoding has been specified using the readable.setEncoding() method or the stream is operating in object mode. The optional
size argument specifies a specific number of bytes to read. If size bytes are not available to be read, null will be returned _unless_ the stream has ended, in which case all of the data remaining in the internal buffer will be returned. If the
size argument is not specified, all of the data contained in the internal buffer will be returned. The
size argument must be less than or equal to 1 GiB. The
readable.read() method should only be called on Readable streams operating in paused mode. In flowing mode, readable.read() is called automatically until the internal buffer is fully drained. ``
js const readable = getReadableStreamSomehow();
// 'readable' may be triggered multiple times as data is buffered in readable.on('readable', () => { let chunk; console.log('Stream is readable (new data received in buffer)'); // Use a loop to make sure we read all currently available data while (null !== (chunk = readable.read())) { console.log(Read ${chunk.length} bytes of data...); } });
// 'end' will be triggered once when there is no more data available readable.on('end', () => { console.log('Reached end of stream.'); }); `
Each call to readable.read() returns a chunk of data, or null. The chunks are not concatenated. A while loop is necessary to consume all data currently in the buffer. When reading a large file .read() may return null, having consumed all buffered content so far, but there is still more data to come not yet buffered. In this case a new 'readable' event will be emitted when there is more data in the buffer. Finally the 'end' event will be emitted when there is no more data to come.
Therefore to read a file's whole contents from a readable, it is necessary to collect chunks across multiple 'readable' events:
`js const chunks = [];
readable.on('readable', () => { let chunk; while (null !== (chunk = readable.read())) { chunks.push(chunk); } });
readable.on('end', () => { const content = chunks.join(''); }); `
A Readable stream in object mode will always return a single item from a call to readable.read(size), regardless of the value of the size argument.
If the readable.read() method returns a chunk of data, a 'data' event will also be emitted.
Calling read after the 'end' event has been emitted will return null`. No runtime error will be raised.Parameters
| Name | Type | Description |
|---|---|---|
§size? | number | Optional argument to specify how much data to read. |
If no initial value is supplied the first chunk of the stream is used as the initial value. If the stream is empty, the promise is rejected with a
TypeError with the ERR_INVALID_ARGS code property. The reducer function iterates the stream element-by-element which means that there is no concurrency parameter or parallelism. To perform a reduce concurrently, you can extract the async function to
readable.map method.Parameters
| Name | Type | Description |
|---|---|---|
§fn | ( | a reducer function to call over every chunk in the stream. Async or not. |
Returns
Promise< T>reduce< T>( fn: ( previous: T, data: any, options?: Abortable) => T, initial: T, options?: Abortable): Promise< T>If no initial value is supplied the first chunk of the stream is used as the initial value. If the stream is empty, the promise is rejected with a
TypeError with the ERR_INVALID_ARGS code property. The reducer function iterates the stream element-by-element which means that there is no concurrency parameter or parallelism. To perform a reduce concurrently, you can extract the async function to
readable.map method.Returns
Promise< T>removeAllListeners< E>( eventName?: E): thiseventName. It is bad practice to remove listeners added elsewhere in the code, particularly when the
EventEmitter instance was created by some other component or module (e.g. sockets or file streams). Returns a reference to the
EventEmitter, so that calls can be chained.Parameters
| Name | Type | Description |
|---|---|---|
§eventName? | E |
removeAllListeners( eventName?: string | symbol): thisParameters
| Name | Type | Description |
|---|---|---|
§eventName? | string | symbol |
removeListener< E>( eventName: E, listener: ( args: indexedAccess) => void): thislistener from the listener array for the event named eventName. ``
js const callback = (stream) => { console.log('someone connected!'); }; server.on('connection', callback); // ... server.removeListener('connection', callback); `
removeListener() will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified eventName, then removeListener() must be called multiple times to remove each instance.
Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any removeListener() or removeAllListeners() calls _after_ emitting and _before_ the last listener finishes execution will not remove them from emit() in progress. Subsequent events behave as expected.
`js import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter();
const callbackA = () => { console.log('A'); myEmitter.removeListener('event', callbackB); };
const callbackB = () => { console.log('B'); };
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called. // Internal listener array at time of emit [callbackA, callbackB] myEmitter.emit('event'); // Prints: // A // B
// callbackB is now removed. // Internal listener array [callbackA] myEmitter.emit('event'); // Prints: // A `
Because listeners are managed using an internal array, calling this will change the position indexes of any listener registered _after_ the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the emitter.listeners() method will need to be recreated.
When a single function has been added as a handler multiple times for a single event (as in the example below), removeListener() will remove the most recently added instance. In the example the once('ping') listener is removed:
`js import { EventEmitter } from 'node:events'; const ee = new EventEmitter();
function pong() { console.log('pong'); }
ee.on('ping', pong); ee.once('ping', pong); ee.removeListener('ping', pong);
ee.emit('ping'); ee.emit('ping'); `
Returns a reference to the EventEmitter`, so that calls can be chained.resume( ): thisreadable.resume() method causes an explicitly paused Readable stream to resume emitting 'data' events, switching the stream into flowing mode. The
readable.resume() method can be used to fully consume the data from a stream without actually processing any of that data: ``
js getReadableStreamSomehow() .resume() .on('end', () => { console.log('Reached the end, but did not read anything.'); }); `
The readable.resume() method has no effect if there is a 'readable'` event listener.setDefaultEncoding( encoding: BufferEncoding): thiswritable.setDefaultEncoding() method sets the default encoding for a Writable stream.Parameters
| Name | Type | Description |
|---|---|---|
§encoding | BufferEncoding | The new default encoding |
setEncoding( encoding: BufferEncoding): thisreadable.setEncoding() method sets the character encoding for data read from the Readable stream. By default, no encoding is assigned and stream data will be returned as
Buffer objects. Setting an encoding causes the stream data to be returned as strings of the specified encoding rather than as Buffer objects. For instance, calling readable.setEncoding('utf8') will cause the output data to be interpreted as UTF-8 data, and passed as strings. Calling readable.setEncoding('hex') will cause the data to be encoded in hexadecimal string format. The
Readable stream will properly handle multi-byte characters delivered through the stream that would otherwise become improperly decoded if simply pulled from the stream as Buffer objects. ``
js const readable = getReadableStreamSomehow(); readable.setEncoding('utf8'); readable.on('data', (chunk) => { assert.equal(typeof chunk, 'string'); console.log('Got %d characters of string data:', chunk.length); }); ``Parameters
| Name | Type | Description |
|---|---|---|
§encoding | BufferEncoding | The encoding to use. |
setMaxListeners( n: number): thisEventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default that helps finding memory leaks. The emitter.setMaxListeners() method allows the limit to be modified for this specific EventEmitter instance. The value can be set to Infinity (or 0) to indicate an unlimited number of listeners. Returns a reference to the
EventEmitter, so that calls can be chained.Parameters
| Name | Type | Description |
|---|---|---|
§n | number |
some( fn: ( data: any, options?: Abortable) => boolean | Promise< boolean>, options?: Pick< ReadableOperatorOptions, "concurrency" | "signal">): Promise< boolean>Array.prototype.some and calls fn on each chunk in the stream until the awaited return value is true (or any truthy value). Once an fn call on a chunk awaited return value is truthy, the stream is destroyed and the promise is fulfilled with true. If none of the fn calls on the chunks return a truthy value, the promise is fulfilled with false.Returns
Promise< boolean>true if fn returned a truthy value for at least one of the chunks.As this method reads the entire stream into memory, it negates the benefits of streams. It's intended for interoperability and convenience, not as the primary way to consume streams.
Parameters
| Name | Type | Description |
|---|---|---|
§options? | Abortable |
Returns
Promise< any[ ]>uncork( ): voidwritable.uncork() method flushes all data buffered since cork was called. When using
writable.cork() and writable.uncork() to manage the buffering of writes to a stream, defer calls to writable.uncork() using process.nextTick(). Doing so allows batching of all writable.write() calls that occur within a given Node.js event loop phase. ``
js stream.cork(); stream.write('some '); stream.write('data '); process.nextTick(() => stream.uncork()); `
If the writable.cork() method is called multiple times on a stream, the same number of calls to writable.uncork() must be called to flush the buffered data.
`js stream.cork(); stream.write('some '); stream.cork(); stream.write('data '); process.nextTick(() => { stream.uncork(); // The data will not be flushed until uncork() is called a second time. stream.uncork(); }); `
See also: writable.cork()`.unpipe( destination?: WritableStream): thisreadable.unpipe() method detaches a Writable stream previously attached using the pipe method. If the
destination is not specified, then _all_ pipes are detached. If the
destination is specified, but no pipe is set up for it, then the method does nothing. ``
js import fs from 'node:fs'; const readable = getReadableStreamSomehow(); const writable = fs.createWriteStream('file.txt'); // All the data from readable goes into 'file.txt', // but only for the first second. readable.pipe(writable); setTimeout(() => { console.log('Stop writing to file.txt.'); readable.unpipe(writable); console.log('Manually close the file stream.'); writable.end(); }, 1000); ``Parameters
| Name | Type | Description |
|---|---|---|
§destination? | WritableStream | Optional specific stream to unpipe |
unshift( chunk: any, encoding?: BufferEncoding): voidchunk as null signals the end of the stream (EOF) and behaves the same as readable.push(null), after which no more data can be written. The EOF signal is put at the end of the buffer and any buffered data will still be flushed. The
readable.unshift() method pushes a chunk of data back into the internal buffer. This is useful in certain situations where a stream is being consumed by code that needs to "un-consume" some amount of data that it has optimistically pulled out of the source, so that the data can be passed on to some other party. The
stream.unshift(chunk) method cannot be called after the 'end' event has been emitted or a runtime error will be thrown. Developers using
stream.unshift() often should consider switching to use of a Transform stream instead. See the API for stream implementers section for more information. ``
js // Pull off a header delimited by \n\n. // Use unshift() if we get too much. // Call the callback with (error, header, stream). import { StringDecoder } from 'node:string_decoder'; function parseHeader(stream, callback) { stream.on('error', callback); stream.on('readable', onReadable); const decoder = new StringDecoder('utf8'); let header = ''; function onReadable() { let chunk; while (null !== (chunk = stream.read())) { const str = decoder.write(chunk); if (str.includes('\n\n')) { // Found the header boundary. const split = str.split(/\n\n/); header += split.shift(); const remaining = split.join('\n\n'); const buf = Buffer.from(remaining, 'utf8'); stream.removeListener('error', callback); // Remove the 'readable' listener before unshifting. stream.removeListener('readable', onReadable); if (buf.length) stream.unshift(buf); // Now the body of the message can be read from the stream. callback(null, header, stream); return; } // Still reading the header. header += str; } } } `
Unlike push, stream.unshift(chunk) will not end the reading process by resetting the internal reading state of the stream. This can cause unexpected results if readable.unshift() is called during a read (i.e. from within a _read implementation on a custom stream). Following the call to readable.unshift() with an immediate push will reset the reading state appropriately, however it is best to simply avoid calling readable.unshift()` while in the process of performing a read.Parameters
| Name | Type | Description |
|---|---|---|
§chunk | any | Chunk of data to unshift onto the read queue. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray}, {DataView} or null. For object mode streams, chunk may be any JavaScript value. |
§encoding? | BufferEncoding | Encoding of string chunks. Must be a valid Buffer encoding, such as 'utf8' or 'ascii'. |
wrap( stream: ReadableStream): thisnode:stream module API as it is currently defined. (See Compatibility for more information.) When using an older Node.js library that emits
'data' events and has a pause method that is advisory only, the readable.wrap() method can be used to create a Readable stream that uses the old stream as its data source. It will rarely be necessary to use
readable.wrap() but the method has been provided as a convenience for interacting with older Node.js applications and libraries. ``
js import { OldReader } from './old-api-module.js'; import { Readable } from 'node:stream'; const oreader = new OldReader(); const myReader = new Readable().wrap(oreader);
myReader.on('readable', () => { myReader.read(); // etc. }); ``Parameters
| Name | Type | Description |
|---|---|---|
§stream | ReadableStream | An "old style" readable stream |
writable.write() method writes some data to the stream, and calls the supplied callback once the data has been fully handled. If an error occurs, the callback will be called with the error as its first argument. The callback is called asynchronously and before 'error' is emitted. The return value is
true if the internal buffer is less than the highWaterMark configured when the stream was created after admitting chunk. If false is returned, further attempts to write data to the stream should stop until the 'drain' event is emitted. While a stream is not draining, calls to
write() will buffer chunk, and return false. Once all currently buffered chunks are drained (accepted for delivery by the operating system), the 'drain' event will be emitted. Once write() returns false, do not write more chunks until the 'drain' event is emitted. While calling write() on a stream that is not draining is allowed, Node.js will buffer all written chunks until maximum memory usage occurs, at which point it will abort unconditionally. Even before it aborts, high memory usage will cause poor garbage collector performance and high RSS (which is not typically released back to the system, even after the memory is no longer required). Since TCP sockets may never drain if the remote peer does not read the data, writing a socket that is not draining may lead to a remotely exploitable vulnerability. Writing data while the stream is not draining is particularly problematic for a
Transform, because the Transform streams are paused by default until they are piped or a 'data' or 'readable' event handler is added. If the data to be written can be generated or fetched on demand, it is recommended to encapsulate the logic into a
Readable and use pipe. However, if calling write() is preferred, it is possible to respect backpressure and avoid memory issues using the 'drain' event: ``
js function write(data, cb) { if (!stream.write(data)) { stream.once('drain', cb); } else { process.nextTick(cb); } }
// Wait for cb to be called before doing any other write. write('hello', () => { console.log('Write completed, do more writes now.'); }); `
A Writable stream in object mode will always ignore the encoding` argument.Parameters
| Name | Type | Description |
|---|---|---|
§chunk | any | Optional data to write. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams, chunk may be any JavaScript value other than null. |
§callback? | ( | Callback for when this chunk of data is flushed. |
Returns
booleanfalse if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.write( chunk: any, encoding: BufferEncoding, callback?: ( error: Error) => void): booleanParameters
| Name | Type | Description |
|---|---|---|
§chunk | any | Optional data to write. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams, chunk may be any JavaScript value other than null. |
§encoding | BufferEncoding | The encoding, if chunk is a string. |
§callback? | ( | Callback for when this chunk of data is flushed. |
Returns
booleanfalse if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.◆ Types
captureStdio takes over, and whether they still print.type StopSignal = "SIGINT" | "SIGTERM"● Variables
The reporter a run names with `--test-reporter`: Node's own spec reporter, with the per-evaluation coverage summary held back so the merged table the runner prints is the only verdict a run shows.
ƒ Functions
Node reports each evaluation of a module as a file of its own, so a suite that calls
jest.resetModules gets one entry per generation and a summary that counts every line of the module once per evaluation. The runner prints the merged table instead, from the lcov report, and printing both would show two different answers for the same run.Parameters
| Name | Type | Description |
|---|---|---|
§source | AsyncIterable< | The test runner's event stream. |
Example
Naming the reporter on a hand-run `node --test`
node --import @hyperfrontend/testing/hooks --test --test-reporter=@hyperfrontend/testing/reporter --test-reporter-destination=stdout src/double.spec.tsThe runner behind a project's `test.config.ts`: one `node --test` run per environment, then the merged coverage report, the threshold gate and the completeness check.
ƒ Functions
buildRunPlan( config: TestConfig, environment: TestEnvironment, projectRoot: string, coverageDir: string): RunPlan
Coverage is always collected: every project used to inherit
collectCoverage: true from the shared preset, so making it conditional would quietly weaken the gate.Parameters
| Name | Type | Description |
|---|---|---|
§config | TestConfig | The project's configuration, with defaults already applied. |
§environment | TestEnvironment | The environment to run. |
§projectRoot | string | Absolute path to the project root. |
§coverageDir | string | Absolute path to the project's coverage output directory. |
Returns
RunPlanExample
Planning a project's only environment
const resolved = withDefaults(config)
const plan = buildRunPlan(resolved, resolved.environments[0], '/repo/libs/example', '/repo/coverage/libs/example')
spawnSync(process.execPath, plan.argv, { cwd: '/repo/libs/example', stdio: 'inherit' })file: URL Node loads on every platform.Parameters
| Name | Type | Description |
|---|---|---|
§path | string | Absolute path to a module. |
Returns
stringfile: address Node accepts as a specifier.Example
Rendering a preload path Node accepts on every platform
moduleUrl('/repo/libs/example/test.setup.ts') // => 'file:///repo/libs/example/test.setup.ts'
// on Windows the same call turns 'C:\\repo\\test.setup.ts' into 'file:///C:/repo/test.setup.ts', where the bare path would parse as a URL with scheme 'c:'Parameters
| Name | Type | Description |
|---|---|---|
§config | TestConfig | The project's configuration. |
§context | RunContext | Where the run happens and where coverage is written. |
Returns
RunOutcomeExample
Running a project and reporting its verdict
const outcome = runProjectTests(config, {
workspaceRoot: '/repo',
projectRoot: '/repo/libs/example',
coverageDir: '/repo/coverage/libs/example',
})
console.log(outcome.coverageTable.join('\n'))
if (!outcome.success) {
console.error(outcome.failures.join('\n'))
process.exitCode = 1
}Node has no way to exclude anything from a
--test glob, so an environment that ignores files cannot express its selection as a pattern and has it expanded here instead. An environment that ignores nothing keeps its globs, which leaves discovery to Node and the argument list readable.Parameters
| Name | Type | Description |
|---|---|---|
§environment | TestEnvironment | The environment being run. |
§projectRoot | string | Absolute path to the project root. |
Returns
string[ ]Example
Expanding globs only when something is ignored
const environment = { name: 'node', testMatch: ['src/**/*.spec.ts'] }
selectSpecFiles(environment, '/repo/libs/example') // => ['src/**/*.spec.ts'], left to Node
selectSpecFiles({ ...environment, testIgnore: ['**/*.browser.spec.ts'] }, '/repo/libs/example')
// => ['src/double.spec.ts', 'src/other.spec.ts'], expanded here because Node cannot exclude files from a globParameters
| Name | Type | Description |
|---|---|---|
§config | TestConfig | The project's configuration. |
Returns
stringExample
Rendering the value of `HF_TEST_MOCK_LIFECYCLE`
serialiseMockLifecycle({ ...config, clearMocks: true, restoreMocks: true }) // => 'clear,restore'moduleNameMapper for the resolution hooks, which read it from the environment because they run in a child process.Parameters
| Name | Type | Description |
|---|---|---|
§config | TestConfig | The project's configuration. |
Returns
stringExample
Rendering the value of `HF_TEST_MODULE_MAP`
serialiseModuleMap({ ...config, moduleNameMapper: { '^\\./real$': '<rootDir>/src/stub.ts' } })
// => '[["^\\\\./real$","<rootDir>/src/stub.ts"]]'
serialiseModuleMap(config) // => undefined when no mapping is declaredThe hooks read
jest.mock out of a file's source as it loads, and they only read it from files they can recognise. A spec is recognisable by its name; a setup module is not, so the runner has to name them.Parameters
| Name | Type | Description |
|---|---|---|
§environment | TestEnvironment | The environment being run. |
§projectRoot | string | Absolute path to the project root. |
Returns
stringExample
Rendering the value of `HF_TEST_SETUP_FILES`
serialiseSetupFiles({ name: 'node', testMatch: ['src/**/*.spec.ts'], setupFiles: ['test.setup.ts'] }, '/repo/libs/example')
// => '["/repo/libs/example/test.setup.ts"]'Parameters
| Name | Type | Description |
|---|---|---|
§environment | TestEnvironment | The environment being run. |
§projectRoot | string | Absolute path to the project root. |
Returns
string[ ]Example
Anchoring setup modules to the project
setupPaths({ name: 'node', testMatch: ['src/**/*.spec.ts'], setupFiles: ['test.setup.ts'] }, '/repo/libs/example')
// => ['/repo/libs/example/test.setup.ts']withDefaults( config: TestConfig): Required< Pick< TestConfig, "coverageExclude" | "testTimeout">> & TestConfig
Parameters
| Name | Type | Description |
|---|---|---|
§config | TestConfig | The configuration as authored. |
Returns
Required< Pick< TestConfig, "coverageExclude" | "testTimeout">> & TestConfigExample
Seeing what a minimal configuration resolves to
const resolved = withDefaults({ environments: [{ name: 'node', testMatch: ['src/**/*.spec.ts'] }], coverageInclude: ['src/**/*.ts'] })
resolved.testTimeout // => 30000
resolved.coverageExclude // => BASELINE_COVERAGE_EXCLUDE, with a project's own exclusions appended after it◆ Types
Node measures lines, branches, and functions. It has no statements metric, so a project's former statements threshold is carried by
lines.jest.config.ts used to hold.A project with both Node-only and DOM-facing suites declares two, each selecting its own files and loading its own setup.
● Variables
Related reading§
- Architecture
Architecture
How @hyperfrontend/testing is put together, and why.
- How-to
How to migrate a Jest suite to Node's test runner
Jest pulls a framework, a transformer and a reporter stack into a project whose runtime already ships a test runner, but rewriting thousands of Jest-style tests into node:test calls is not an option.
- How-to
How to configure and run TypeScript tests on Node's test runner
node:test runs TypeScript files through type stripping, but it resolves no extensionless imports or path aliases, has no environment concept for a DOM, and lets a file nobody tested through a full-coverage gate.
- How-to
How to test a package the way a consumer installs it
My library passes every test in the workspace, where path aliases, loader hooks and a hoisted node_modules resolve whatever the source asks for, and then a consumer runs npm install and the published entry fails to load or throws on the first call.
- How-to
How to write focused tests with mocks, fake timers and module replacements
My tests pass, but when one fails I cannot tell what broke: each test checks several things, timers are awaited for real, and the module a function depends on cannot be replaced without restructuring the code.
- Tutorial
Set up a monorepo and test only what changed
A repository of several TypeScript libraries runs every test on every change, because nothing knows which libraries a change actually reaches.
- Getting started
Getting Started
Set HyperFrontend up and embed a first feature.
- Architecture
Architecture Guide
How the packages fit together.

