Class Test<Ext, Opts>

This is the class that is extended for the root @tapjs/core!tap.TAP test, and used to instantiate test objects in its child tests. It extends @tapjs/core!test-base.TestBase, and implements the union of return values of all loaded plugins via a Proxy.

Type Parameters

Hierarchy (view full)

Implements

Constructors

Properties

Accessors

Methods

Assertion Methods

Internal Machinery

Plugin Management

Spies, Mocks, and Fixtures

Subtest Methods

Test Lifecycle Management

Test Reflection

Constructors

Properties

#private: any
#private: any
#private: any
#private: any
#private: any
#private: any
#private: any
#private: any
#private: any
#private: any
#private: any
#private: any
#private: any
#private: any
#private: any
#private: any
[ABORTED]: boolean
[ASYNC]: boolean
[BUFFERLENGTH]: number
[BUFFER]: string[]
[CLOSED]: boolean
[DATALISTENERS]: number
[DECODER]: null | SD
[DESTROYED]: boolean
[DISCARDED]: boolean
[EMITTED_END]: boolean
[EMITTED_ERROR]: unknown
[EMITTING_END]: boolean
[ENCODING]: null | BufferEncoding
[EOF]: boolean
[FLOWING]: boolean
[OBJECTMODE]: boolean
[PAUSED]: boolean
[PIPES]: Pipe<string>[]
[SIGNAL]?: AbortSignal
bail: boolean

Bail out on the first failed test point

childId: number

Numeric identifier for this test

debug: ((...args) => void)

Method that writes to stderr when debug: true is set in the options, or no-ops otherwise

Type declaration

    • (...args): void
    • Parameters

      • Rest ...args: any[]

      Returns void

diagnostic: null | boolean

Show diagnostics for this test. A value of null means that diagnostics will be shown only if the test is failing.

ended: boolean

Set true when @tapjs/core!test-base.TestBase#end is called

indent: string

number of spaces to indent the TAP stream

nestingLevel: number

Nesting level, for serialization to node test runner

Note that this is zero for parent-less tests, and also zero for the first level of children.

omitVersion: boolean

Do not emit the TAP version 14 line at the start

options: TestBaseOpts

Options provided to this test

parent?: TestBase

Parent test of this TAP stream

preserveWhitespace: boolean

Do not elide extraneous whitespace and empty lines.

readable: boolean

true if the stream can be read

readyToProcess: boolean

Set upon test completion when a child test is ready to be processed by its parent.

silent: boolean

True if this test should be buffered and only emit data if it fails

strict: boolean

Treat non-TAP data as an error. May be set with pragma +strict in the TAP stream, or unset with pragma: -strict.

timedOut: boolean

Set to true when the test times out, so its failure status can be determined later.

writable: boolean

true if the stream can be written

writeSnapshot: boolean
captureRejectionSymbol: typeof captureRejectionSymbol

Value: Symbol.for('nodejs.rejection')

See how to write a custom rejection handler.

Since

v13.4.0, v12.16.0

captureRejections: boolean

Value: boolean

Change the default captureRejections option on all new EventEmitter objects.

Since

v13.4.0, v12.16.0

defaultMaxListeners: number

By default, a maximum of 10 listeners can be registered for any single event. This limit can be changed for individual EventEmitter instances using the emitter.setMaxListeners(n) method. To change the default for allEventEmitter instances, the events.defaultMaxListenersproperty can be used. If this value is not a positive number, a RangeErroris thrown.

Take caution when setting the events.defaultMaxListeners because the change affects allEventEmitter instances, including those created before the change is made. However, calling emitter.setMaxListeners(n) still has precedence over events.defaultMaxListeners.

This is not a hard limit. The EventEmitter instance will allow more listeners to be added but will output a trace warning to stderr indicating that a "possible EventEmitter memory leak" has been detected. For any singleEventEmitter, the emitter.getMaxListeners() and emitter.setMaxListeners()methods can be used to temporarily avoid this warning:

import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});

The --trace-warnings command-line flag can be used to display the stack trace for such warnings.

The emitted warning can be inspected with process.on('warning') and will have the additional emitter, type, and count properties, referring to the event emitter instance, the event's name and the number of attached listeners, respectively. Its name property is set to 'MaxListenersExceededWarning'.

Since

v0.11.2

errorMonitor: typeof errorMonitor

This symbol shall be used to install a listener for only monitoring 'error'events. Listeners installed using this symbol are called before the regular'error' listeners are called.

Installing a listener using this symbol does not change the behavior once an'error' event is emitted. Therefore, the process will still crash if no regular 'error' listener is installed.

Since

v13.6.0, v12.17.0

Accessors

  • get aborted(): boolean
  • True if the stream has been aborted.

    Returns boolean

  • set aborted(_): void
  • No-op setter. Stream aborted status is set via the AbortSignal provided in the constructor options.

    Parameters

    • _: boolean

    Returns void

  • get async(): boolean
  • true if this is an async stream

    Returns boolean

  • set async(a): void
  • Set to true to make this stream async.

    Once set, it cannot be unset, as this would potentially cause incorrect behavior. Ie, a sync stream can be made async, but an async stream cannot be safely made sync.

    Parameters

    • a: boolean

    Returns void

  • get bufferLength(): number
  • The amount of data stored in the buffer waiting to be read.

    For Buffer strings, this will be the total byte length. For string encoding streams, this will be the string character length, according to JavaScript's string.length logic. For objectMode streams, this is a count of the items waiting to be emitted.

    Returns number

  • get cleanSnapshot(): undefined | ((snapshotData) => string)
  • Method that will be called on snapshot strings. This can be used to remove transient run-specific data from snapshots using simple string transforms.

    Returns undefined | ((snapshotData) => string)

  • set cleanSnapshot(clean): void
  • Parameters

    • clean: undefined | ((snapshotData) => string)

    Returns void

  • get compareOptions(): CompareOptions
  • Options that will be used when formatting snapshots and diffing/comparing objects using any assertion methods.

    Returns CompareOptions

  • set compareOptions(cmt): void
  • Parameters

    Returns void

  • get destroyed(): boolean
  • true if the stream has been forcibly destroyed

    Returns boolean

  • get emittedEnd(): boolean
  • true if the 'end' event has been emitted

    Returns boolean

  • get encoding(): null | BufferEncoding
  • The BufferEncoding currently in use, or null

    Returns null | BufferEncoding

  • set encoding(_enc): void
  • Parameters

    • _enc: null | BufferEncoding

    Returns void

    Deprecated

    • This is a read only property
  • get flowing(): boolean
  • true if the stream is currently in a flowing state, meaning that any writes will be immediately emitted.

    Returns boolean

  • get formatSnapshot(): undefined | ((obj) => any)
  • Function that turns an object into a snapshot string.

    By default tcompare!format is used. If a string is returned, then that string is the snapshot string. If any other type is returned, then the returned value will be formatted using tcompare!format.

    Returns undefined | ((obj) => any)

  • set formatSnapshot(format): void
  • Parameters

    • format: undefined | ((obj) => any)

    Returns void

  • get fullname(): string
  • The full name of the test, starting with the main script name, and including all parent names.

    Returns string

  • get objectMode(): boolean
  • True if this is an objectMode stream

    Returns boolean

  • set objectMode(_om): void
  • Parameters

    • _om: boolean

    Returns void

    Deprecated

    • This is a read-only property
  • get paused(): boolean
  • true if the stream is currently in a paused state

    Returns boolean

  • get runOnly(): boolean
  • Returns boolean

  • set runOnly(o): void
  • Parameters

    • o: boolean

    Returns void

  • get saveFixture(): boolean
  • Returns boolean

  • set saveFixture(save): void
  • Set whether the fixture should be saved or not

    Must be set BEFORE calling @tapjs/fixture!index.TestFixtures#testdir, or it will not have any effect.

    Parameters

    • save: boolean

    Returns void

  • get snapshotFile(): string
  • The file where snapshots will be written to and read from

    Returns string

  • set snapshotFile(f): void
  • Parameters

    • f: string | URL

    Returns void

  • get streamWritable(): boolean
  • Boolean indicating whether the underlying stream can be written to, or if it has been ended.

    Returns boolean

  • get workerData(): any
  • In the worker thread, the worker data that was provided to the t.worker method.

    In the main thread, this field is undefined.

    Returns any

  • get isStream(): ((s) => s is WriteStream | ReadStream | Minipass<any, any, any> | ReadStream & {
        fd: number;
    } | EventEmitter<DefaultEventMap> & {
        pause(): any;
        pipe(...destArgs): any;
        resume(): any;
    } | WriteStream & {
        fd: number;
    } | EventEmitter<DefaultEventMap> & {
        end(): any;
        write(chunk, ...args): any;
    })
  • Alias for isStream

    Former export location, maintained for backwards compatibility.

    Returns ((s) => s is WriteStream | ReadStream | Minipass<any, any, any> | ReadStream & {
        fd: number;
    } | EventEmitter<DefaultEventMap> & {
        pause(): any;
        pipe(...destArgs): any;
        resume(): any;
    } | WriteStream & {
        fd: number;
    } | EventEmitter<DefaultEventMap> & {
        end(): any;
        write(chunk, ...args): any;
    })

      • (s): s is WriteStream | ReadStream | Minipass<any, any, any> | ReadStream & {
            fd: number;
        } | EventEmitter<DefaultEventMap> & {
            pause(): any;
            pipe(...destArgs): any;
            resume(): any;
        } | WriteStream & {
            fd: number;
        } | EventEmitter<DefaultEventMap> & {
            end(): any;
            write(chunk, ...args): any;
        }
      • Parameters

        • s: any

        Returns s is WriteStream | ReadStream | Minipass<any, any, any> | ReadStream & {
            fd: number;
        } | EventEmitter<DefaultEventMap> & {
            pause(): any;
            pipe(...destArgs): any;
            resume(): any;
        } | WriteStream & {
            fd: number;
        } | EventEmitter<DefaultEventMap> & {
            end(): any;
            write(chunk, ...args): any;
        }

    Deprecated

Methods

  • Returns void

  • Parameters

    • chunk: string

    Returns void

  • Returns string

  • Parameters

    • data: string

    Returns boolean

  • Returns boolean

  • Returns boolean

  • Parameters

    • chunk: string

    Returns boolean

  • Parameters

    • Optional noDrain: boolean

    Returns void

  • Returns void

  • Parameters

    • n: null | number
    • chunk: string

    Returns string

  • Returns void

  • Asynchronous for await of iteration.

    This will continue emitting all chunks until the stream terminates.

    Returns AsyncGenerator<string, void, void>

  • Type Parameters

    • K

    Parameters

    • error: Error
    • event: string | symbol
    • Rest ...args: AnyRest

    Returns void

  • Synchronous for of iteration.

    The iteration will terminate when the internal buffer runs out, even if the stream has not yet terminated.

    Returns Generator<string, void, void>

  • Return a Promise that resolves to an array of all emitted data once the stream ends.

    Returns Promise<string[] & {
        dataLength: number;
    }>

  • output a TAP comment, formatted like console.log()

    If the test is currently awaiting a child test, it will be deferred until after the child test completes.

    If the test is already completed, the comment will be emitted on the parent, or if no parent is available, it will be printed to standard output.

    Parameters

    • Rest ...args: any[]

    Returns void

  • Return a Promise that resolves to the concatenation of all emitted data once the stream ends.

    Not allowed on objectMode streams.

    Returns Promise<string>

  • Destroy a stream, preventing it from being used for any further purpose.

    If the stream has a close() method, then it will be called on destruction.

    After destruction, any attempt to write data, read data, or emit most events will be ignored.

    If an error argument is provided, then it will be emitted in an 'error' event.

    Parameters

    • Optional er: unknown

    Returns this

  • Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or Symbols.

    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) ]

    Returns (string | symbol)[]

    Since

    v6.0.0

  • Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.

    Returns number

    Since

    v1.0.0

  • Returns the number of listeners listening for the event named eventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

      The name of the event being listened for

    • Optional listener: Function

      The event handler function

    Returns number

    Since

    v3.2.0

  • Returns a copy of the array of listeners for the event named eventName.

    server.on('connection', (stream) => {
    console.log('someone connected!');
    });
    console.log(util.inspect(server.listeners('connection')));
    // Prints: [ [Function] ]

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

    Returns Function[]

    Since

    v0.1.26

  • Set some mocks that will be used for all subsequent @tapjs/mock!index.TapMock#mockImport and @tapjs/mock!index.TapMock#mockRequire calls made by this test.

    Mocks added with mockAll are overridden by any explicit mocks set in the t.mockRequire or t.mockImport call.

    Repeated calls to t.mockAll() will add mocks to the set. If the same name is used again, it will replace the previous value, not merge.

    If a key is set to undefined or null, then it will be removed from the mockAll set.

    Reset by calling t.mockAll(null)

    Call with no args to return the current mockAll object.

    Parameters

    • Optional mocks: null | Record<string, any>

    Returns Record<string, any>

  • Mostly identical to EventEmitter.off

    If a 'data' event handler is removed, and it was the last consumer (ie, there are no pipe destinations or other 'data' event listeners), then the flow of data will stop until there is another consumer or Minipass#resume is explicitly called.

    Type Parameters

    Parameters

    Returns this

  • Mostly identical to EventEmitter.on, with the following behavior differences to prevent data loss and unnecessary hangs:

    • Adding a 'data' event handler will trigger the flow of data

    • Adding a 'readable' event handler when there is data waiting to be read will cause 'readable' to be emitted immediately.

    • Adding an 'endish' event handler ('end', 'finish', etc.) which has already passed will cause the event to be emitted immediately and all handlers removed.

    • Adding an 'error' event handler after an error has been emitted will cause the event to be re-emitted immediately with the error previously raised.

    Type Parameters

    Parameters

    Returns this

  • Adds a one-timelistener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.

    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. Theemitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

    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

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

      The name of the event.

    • listener: ((...args) => void)

      The callback function

        • (...args): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns this

    Since

    v0.3.0

  • Pause the stream

    Returns void

  • Pipe all data emitted by this stream into the destination provided.

    Triggers the flow of data.

    Type Parameters

    • W extends Writable

    Parameters

    • dest: W
    • Optional opts: PipeOptions

    Returns W

  • Set TAP pragma configs to affect the behavior of the parser. Only strict is supported by the parser.

    Parameters

    • set: {
          [k: string]: boolean;
      }
      • [k: string]: boolean

    Returns void

  • Adds the listener 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 eventNameand listener will result in the listener being added, and called, multiple times.

    server.prependListener('connection', (stream) => {
    console.log('someone connected!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

      The name of the event.

    • listener: ((...args) => void)

      The callback function

        • (...args): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns this

    Since

    v6.0.0

  • Adds a one-timelistener 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.

    server.prependOnceListener('connection', (stream) => {
    console.log('Ah, we have our first user!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

      The name of the event.

    • listener: ((...args) => void)

      The callback function

        • (...args): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns this

    Since

    v6.0.0

  • Return a void Promise that resolves once the stream ends.

    Returns Promise<void>

  • Returns a copy of the array of listeners for the event named eventName, including any wrappers (such as those created by .once()).

    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');

    Type Parameters

    • K

    Parameters

    • eventName: string | symbol

    Returns Function[]

    Since

    v9.4.0

  • Low-level explicit read method.

    In objectMode, the argument is ignored, and one item is returned if available.

    n is the number of bytes (or in the case of encoding streams, characters) to consume. If n is not provided, then the entire buffer is returned, or null is returned if no data is available.

    If n is greater that the amount of data in the internal buffer, then null is returned.

    Parameters

    • Optional n: null | number

    Returns null | string

  • Mostly identical to EventEmitter.removeAllListeners

    If all 'data' event handlers are removed, and they were the last consumer (ie, there are no pipe destinations), then the flow of data will stop until there is another consumer or Minipass#resume is explicitly called.

    Type Parameters

    Parameters

    Returns this

  • Resume the stream if it is currently in a paused state

    If called when there are no pipe destinations or data event listeners, this will place the stream in a "discarded" state, where all data will be thrown away. The discarded state is removed if a pipe destination or data handler is added, if pause() is called, or if any synchronous or asynchronous iteration is started.

    Returns void

  • Parameters

    • _enc: Encoding

    Returns void

    Deprecated

    • Encoding may only be set at instantiation time
  • By default EventEmitters 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 toInfinity (or 0) to indicate an unlimited number of listeners.

    Returns a reference to the EventEmitter, so that calls can be chained.

    Parameters

    • n: number

    Returns this

    Since

    v0.3.5

  • Fully unhook a piped destination stream.

    If the destination stream was the only consumer of this stream (ie, there are no other piped destinations or 'data' event listeners) then the flow of data will stop until there is another consumer or Minipass#resume is explicitly called.

    Type Parameters

    • W extends Writable

    Parameters

    • dest: W

    Returns void

  • Experimental

    Listens once to the abort event on the provided signal.

    Listening to the abort event on abort signals is unsafe and may lead to resource leaks since another third party with the signal can call e.stopImmediatePropagation(). Unfortunately Node.js cannot change this since it would violate the web standard. Additionally, the original API makes it easy to forget to remove listeners.

    This API allows safely using AbortSignals in Node.js APIs by solving these two issues by listening to the event such that stopImmediatePropagation does not prevent the listener from running.

    Returns a disposable so that it may be unsubscribed from more easily.

    import { addAbortListener } from 'node:events';

    function example(signal) {
    let disposable;
    try {
    signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
    disposable = addAbortListener(signal, (e) => {
    // Do something when signal is aborted.
    });
    } finally {
    disposable?.[Symbol.dispose]();
    }
    }

    Parameters

    • signal: AbortSignal
    • resource: ((event) => void)
        • (event): void
        • Parameters

          • event: Event

          Returns void

    Returns Disposable

    Disposable that removes the abort listener.

    Since

    v20.5.0

  • Returns a copy of the array of listeners for the event named eventName.

    For EventEmitters this behaves exactly the same as calling .listeners on the emitter.

    For EventTargets this is the only way to get the event listeners for the event target. This is useful for debugging and diagnostic purposes.

    import { getEventListeners, EventEmitter } from 'node:events';

    {
    const ee = new EventEmitter();
    const listener = () => console.log('Events are fun');
    ee.on('foo', listener);
    console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
    }
    {
    const et = new EventTarget();
    const listener = () => console.log('Events are fun');
    et.addEventListener('foo', listener);
    console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
    }

    Parameters

    • emitter: EventEmitter<DefaultEventMap> | _DOMEventTarget
    • name: string | symbol

    Returns Function[]

    Since

    v15.2.0, v14.17.0

  • Returns the currently set max amount of listeners.

    For EventEmitters this behaves exactly the same as calling .getMaxListeners on the emitter.

    For EventTargets this is the only way to get the max event listeners for the event target. If the number of event handlers on a single EventTarget exceeds the max set, the EventTarget will print a warning.

    import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';

    {
    const ee = new EventEmitter();
    console.log(getMaxListeners(ee)); // 10
    setMaxListeners(11, ee);
    console.log(getMaxListeners(ee)); // 11
    }
    {
    const et = new EventTarget();
    console.log(getMaxListeners(et)); // 10
    setMaxListeners(11, et);
    console.log(getMaxListeners(et)); // 11
    }

    Parameters

    • emitter: EventEmitter<DefaultEventMap> | _DOMEventTarget

    Returns number

    Since

    v19.9.0

  • A class method that returns the number of listeners for the given eventNameregistered on the given emitter.

    import { EventEmitter, listenerCount } from 'node:events';

    const myEmitter = new EventEmitter();
    myEmitter.on('event', () => {});
    myEmitter.on('event', () => {});
    console.log(listenerCount(myEmitter, 'event'));
    // Prints: 2

    Parameters

    • emitter: EventEmitter<DefaultEventMap>

      The emitter to query

    • eventName: string | symbol

      The event name

    Returns number

    Since

    v0.9.12

    Deprecated

    Since v3.2.0 - Use listenerCount instead.

  • import { on, EventEmitter } from 'node:events';
    import process from 'node:process';

    const ee = new EventEmitter();

    // Emit later on
    process.nextTick(() => {
    ee.emit('foo', 'bar');
    ee.emit('foo', 42);
    });

    for await (const event of on(ee, 'foo')) {
    // The execution of this inner block is synchronous and it
    // processes one event at a time (even with await). Do not use
    // if concurrent execution is required.
    console.log(event); // prints ['bar'] [42]
    }
    // Unreachable here

    Returns an AsyncIterator that iterates eventName events. It will throw if the EventEmitter emits 'error'. It removes all listeners when exiting the loop. The value returned by each iteration is an array composed of the emitted event arguments.

    An AbortSignal can be used to cancel waiting on events:

    import { on, EventEmitter } from 'node:events';
    import process from 'node:process';

    const ac = new AbortController();

    (async () => {
    const ee = new EventEmitter();

    // Emit later on
    process.nextTick(() => {
    ee.emit('foo', 'bar');
    ee.emit('foo', 42);
    });

    for await (const event of on(ee, 'foo', { signal: ac.signal })) {
    // The execution of this inner block is synchronous and it
    // processes one event at a time (even with await). Do not use
    // if concurrent execution is required.
    console.log(event); // prints ['bar'] [42]
    }
    // Unreachable here
    })();

    process.nextTick(() => ac.abort());

    Parameters

    • emitter: EventEmitter<DefaultEventMap>
    • eventName: string

      The name of the event being listened for

    • Optional options: StaticEventEmitterOptions

    Returns AsyncIterableIterator<any>

    that iterates eventName events emitted by the emitter

    Since

    v13.6.0, v12.16.0

  • Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. The Promise will resolve with an array of all the arguments emitted to the given event.

    This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error' event semantics and does not listen to the 'error' event.

    import { once, EventEmitter } from 'node:events';
    import process from 'node:process';

    const ee = new EventEmitter();

    process.nextTick(() => {
    ee.emit('myevent', 42);
    });

    const [value] = await once(ee, 'myevent');
    console.log(value);

    const err = new Error('kaboom');
    process.nextTick(() => {
    ee.emit('error', err);
    });

    try {
    await once(ee, 'myevent');
    } catch (err) {
    console.error('error happened', err);
    }

    The special handling of the 'error' event is only used when events.once()is used to wait for another event. If events.once() is used to wait for the 'error' event itself, then it is treated as any other kind of event without special handling:

    import { EventEmitter, once } from 'node:events';

    const ee = new EventEmitter();

    once(ee, 'error')
    .then(([err]) => console.log('ok', err.message))
    .catch((err) => console.error('error', err.message));

    ee.emit('error', new Error('boom'));

    // Prints: ok boom

    An AbortSignal can be used to cancel waiting for the event:

    import { EventEmitter, once } from 'node:events';

    const ee = new EventEmitter();
    const ac = new AbortController();

    async function foo(emitter, event, signal) {
    try {
    await once(emitter, event, { signal });
    console.log('event emitted!');
    } catch (error) {
    if (error.name === 'AbortError') {
    console.error('Waiting for the event was canceled!');
    } else {
    console.error('There was an error', error.message);
    }
    }
    }

    foo(ee, 'foo', ac.signal);
    ac.abort(); // Abort waiting for the event
    ee.emit('foo'); // Prints: Waiting for the event was canceled!

    Parameters

    • emitter: _NodeEventTarget
    • eventName: string | symbol
    • Optional options: StaticEventEmitterOptions

    Returns Promise<any[]>

    Since

    v11.13.0, v10.16.0

  • Parameters

    • emitter: _DOMEventTarget
    • eventName: string
    • Optional options: StaticEventEmitterOptions

    Returns Promise<any[]>

  • import { setMaxListeners, EventEmitter } from 'node:events';

    const target = new EventTarget();
    const emitter = new EventEmitter();

    setMaxListeners(5, target, emitter);

    Parameters

    • Optional n: number

      A non-negative number. The maximum number of listeners per EventTarget event.

    • Rest ...eventTargets: (EventEmitter<DefaultEventMap> | _DOMEventTarget)[]

    Returns void

    Since

    v15.4.0

Assertion Methods

  • Returns the error object if it throws and that does not fail the test (by virtue of being marked skip or todo). Otherwise returns the passing status, like other assertions.

    Parameters

    • fn: Function | (() => any)
    • Rest ...__namedParameters: MessageExtra

    Returns boolean | Error

  • Asserts that the emitter emits the specified event before the test ends. Returns a promise that resolves when the event is emitted. Note that waiting on the returned promise within a test can deadlock the test, if the event never emits, but the returned promise can be a handy way to pause a test until an event happens, if you are reasonably confident that it will fire.

    Parameters

    • emitter: EventEmitter<DefaultEventMap> | EventTarget
    • event: string
    • Rest ...__namedParameters: MessageExtra

    Returns Promise<void>

  • Verify that the values are equal

    Type Parameters

    • T extends unknown

    Parameters

    Returns found is T

  • Verify that the object has all of the properties and values in the pattern, matching loosely.

    Parameters

    • found: any
    • wanted: any
    • Rest ...__namedParameters: MessageExtra

    Returns boolean

  • Verify that the object has the wanted property, using Object#hasOwnProperty

    Type Parameters

    • T extends {}

    Parameters

    • found: T
    • wanted: string | number | symbol
    • Rest ...__namedParameters: MessageExtra

    Returns boolean

  • Verify that the object has all of the properties listed in the wanted list, using Object#hasOwnProperties()

    Type Parameters

    • T extends {}

    Parameters

    • found: T
    • wanted: Iterable<string | number | symbol>
    • Rest ...__namedParameters: MessageExtra

    Returns boolean

  • Verify that the object has all of the properties listed in the wanted list, using Object#hasOwnProperties(), and no others

    Type Parameters

    • T extends {}

    Parameters

    • found: T
    • wanted: Iterable<string | number | symbol>
    • Rest ...__namedParameters: MessageExtra

    Returns boolean

  • Verify that the object has the wanted property, anywhere in its prototype chain.

    Type Parameters

    • T extends {}

    Parameters

    • found: T
    • wanted: string | number | symbol
    • Rest ...__namedParameters: MessageExtra

    Returns boolean

  • Verify that the object has all of the properties in the wanted list, anywhere in its prototype chain.

    Type Parameters

    • T extends {}

    Parameters

    • found: T
    • wanted: Iterable<string | number | symbol>
    • Rest ...__namedParameters: MessageExtra

    Returns boolean

  • Verify that the value has all of the properties and values in the pattern, matching strictly.

    Parameters

    • found: any
    • wanted: any
    • Rest ...__namedParameters: MessageExtra

    Returns boolean

  • Verify that the value matches the pattern provided

    Parameters

    • found: any
    • wanted: any
    • Rest ...__namedParameters: MessageExtra

    Returns boolean

  • Verify that the value matches the pattern provided, with no extra properties.

    Parameters

    • found: any
    • wanted: any
    • Rest ...__namedParameters: MessageExtra

    Returns boolean

  • Verify that the value matches the pattern provided, with no extra properties.

    Parameters

    • found: any
    • wanted: any
    • Rest ...__namedParameters: MessageExtra

    Returns boolean

  • In --snapshot mode, takes a snapshot of the object provided, and writes to the snapshot file.

    Otherwise, reads the snapshot file, and verifies that a snapshot of the object provided matches the stored snapshot.

    Parameters

    Returns boolean

  • Verify that the value matches the pattern provided, but fail if any fields only match via type coercion.

    For example,

    t.matchStrict({ a: 1 }, { a: Number }, 'this passes')
    t.matchStrict({ a: 1 }, { a: '1' }, 'this fails')

    Parameters

    • found: any
    • wanted: any
    • Rest ...__namedParameters: MessageExtra

    Returns boolean

  • Verify that the values are not equal

    Parameters

    • found: any
    • doNotWant: any
    • Rest ...__namedParameters: MessageExtra

    Returns boolean

  • Verify that the object does NOT have all of the properties and values in the pattern, matching loosely.

    Parameters

    • found: any
    • doNotWant: any
    • Rest ...__namedParameters: MessageExtra

    Returns boolean

  • Verify that the value does NOT contain all of the properties and values in the test pattern, comparing strictly.

    Note that this will pass if the value has some of the listed properties, or if they do not match the same type.

    Parameters

    • found: any
    • doNotWant: any
    • Rest ...__namedParameters: MessageExtra

    Returns boolean

  • Verify that the value does NOT match the pattern provided.

    Parameters

    • found: any
    • doNotWant: any
    • Rest ...__namedParameters: MessageExtra

    Returns boolean

  • Verify that the value does not match the pattern provided, with no extra properties. Ie, it might either not match, or have extra props.

    Parameters

    • found: any
    • doNotWant: any
    • Rest ...__namedParameters: MessageExtra

    Returns boolean

  • Verify that the value does not match the pattern provided, with no extra properties. Ie, it might either not match, or have extra props.

    Parameters

    • found: any
    • doNotWant: any
    • Rest ...__namedParameters: MessageExtra

    Returns boolean

  • Verify that the value does not match the pattern provided, without type coercion.

    Parameters

    • found: any
    • doNotWant: any
    • Rest ...__namedParameters: MessageExtra

    Returns boolean

  • Verify that the value is not truthy

    Parameters

    Returns boolean

  • Verify that the value is not loosely equivalent to the supplied pattern

    Parameters

    • found: any
    • doNotWant: any
    • Rest ...__namedParameters: MessageExtra

    Returns boolean

  • Verify that the value is truthy

    Parameters

    Returns boolean

  • resolves to the error object rejected if it rejects as expected, 'false' if it does not, or 'true' if it fails to reject but is marked as skip/todo.

    Type Parameters

    • T extends unknown = any

    Parameters

    • fnOrPromise: (() => Promise<T>) | Promise<T>
    • Rest ...__namedParameters: ThrowsArgs

    Returns Promise<boolean | Error>

  • Test the resolved promise result with t.match()

    Resolves to true if it passes, false if the promise rejects or the match fails, or the rejection error value if the promise rejects but the assertion passes by being marked todo/skip.

    Type Parameters

    • T extends unknown = any

    Parameters

    • fnOrPromise: Promise<T> | (() => Promise<T>)
    • wanted: any
    • Rest ...__namedParameters: MessageExtra

    Returns Promise<boolean>

  • Resolve a promise, and verify that the resulting value matches the snapshot.

    Type Parameters

    • T extends unknown = any

    Parameters

    • fnOrPromise: Promise<T> | (() => Promise<T>)
    • Rest ...__namedParameters: MessageExtra

    Returns Promise<boolean>

  • Resolves to 'true' if the promise resolves successfully, 'false' if it rejects and fails, or the rejection error if it rejects but the failure is accepted by by being marked todo or skip

    Type Parameters

    • T extends unknown = any

    Parameters

    • fnOrPromise: Promise<T> | (() => Promise<T>)
    • Rest ...__namedParameters: MessageExtra

    Returns Promise<boolean | Error>

  • Verify that the value is loosely equivalent to the supplied pattern

    Parameters

    • found: any
    • wanted: any
    • Rest ...__namedParameters: MessageExtra

    Returns boolean

  • Verify that the value is not strictly equivalent to the supplied pattern object

    Parameters

    • found: any
    • doNotWant: any
    • Rest ...__namedParameters: MessageExtra

    Returns boolean

  • Verify that the value is strictly equivalent to the supplied pattern

    Type Parameters

    • T extends unknown

    Parameters

    Returns found is T

  • Verify that the function throws an error. Thrown error is tested against the wanted param if provided, using t.match().

    Returns false on failure, or the error object thrown on success

    Parameters

    • fn: Function | (() => any)
    • Rest ...__namedParameters: ThrowsArgs

    Returns boolean | Error

  • Verify that the value is of the type specified Type can be either a string, or a constructor.

    If a string, then it can match either the typeof result or 'null' for null values, or the name property of the object's constructor.

    Parameters

    • obj: any
    • klass: string | Function
    • Rest ...__namedParameters: MessageExtra

    Returns boolean

Internal Machinery

activeSubtests: Set<Base<TapBaseEvents>>

Subtests that are currently in process.

buffered: boolean

True if this test should be buffered and only processed on completion

cb?: ((...args) => any)

Function that will get this test as an argument when it is processed

Type declaration

    • (...args): any
    • Parameters

      • Rest ...args: any[]

      Returns any

deferred?: Deferred<FinalResults>

A Deferred promise wrapper that is resolved when this test completes.

donePromise?: Promise<any> & {
    tapAbortPromise?: (() => void);
}

A promise that resolves when the test is done.

Type declaration

  • Optional tapAbortPromise?: (() => void)
      • (): void
      • Returns void

hook: TapWrap

TapWrap AsyncResource that limits the async-hook-domain

hookDomain: Domain

the async-hook-domain that catches throws and Promise rejections

output: string

the TAP stream data for buffered tests

parser: Parser

The tap parser attached to this TAP stream

pool: Set<Base<TapBaseEvents>>

The pool of parallel tests currently in process

queue: QueueEntry[]

Queue of items awaiting processing. Can be any @tapjs/core!test-base.QueueEntry item.

start: bigint

high resolution bigint time when this test started

subtests: Base<TapBaseEvents>[]

Array of all subtests that have been added/scheduled, and have not yet completed.

timer?: Timeout

The timer that fires when the test times out

  • get currentAssert(): undefined | Function | ((...a) => any)
  • The current assertion being processed. Set at the start of all assertions, and used for calculating stack traces.

    Returns undefined | Function | ((...a) => any)

  • set currentAssert(fn): void
  • Parameters

    • fn: undefined | Function | ((...a) => any)

    Returns void

  • Internal

    The main function that starts a test running. Generally no need to call this directly.

    Parameters

    • cb: (() => void)
        • (): void
        • Returns void

    Returns void

  • Internal

    extension point for plugins that want to be notified when the test is completely done, and terminating its parser.

    Returns void | Promise<void>

  • Internal

    extension point for plugins that want to be notified when the test is about to end, whether explicitly or implicitly.

    If the function returns a Promise, it will be awaited before ending the TAP stream.

    Returns void | Promise<void>

  • Internal

    extension point for TestBase to know when a child tests is done being processed and it's safe to move on to the next one.

    Returns void

  • Internal

    Method called when an unrecoverable error is encountered in a test.

    Typically, in tests you would not call this, you'd just actually throw an error.

    Parameters

    • er: any
    • Optional extra: Extra
    • Optional proxy: boolean

    Returns undefined | void | Extra

  • Internal

    Called when the test times out. Options are passed as diagnostics to the threw() method

    Parameters

    • Optional options: Extra & {
          expired?: string;
      }

    Returns void

  • Internal

    Await the end of a Promise before proceeding. The supplied callback is called with the Waiter object.

    This is internal, used in some plugins when a promise must be awaited before proceeding. In normal test usage, it's usually best to simply use an async test function and await promises as normal.

    Parameters

    • promise: Promise<any>
    • Optional cb: ((w) => any)
        • (w): any
        • Parameters

          Returns any

    • Optional expectReject: boolean

    Returns Promise<void>

Plugin Management

  • Add a plugin at run-time.

    Creates a subclass of @tapjs/test!index.Test which has the specified plugin, and which applies the plugin to all child tests it creates.

    Typically, it's best to load plugins using configuration, set via the tap plugin <add|rm> command.

    However, in some cases, for example while developing plugins or if a certain plugin is only needed in a small number of tests, it can be useful to apply it after the fact.

    This is best used sparingly, as it may result in poor typescript compilation performance, which can manifest in slower test start-up times and lag loading autocomplete in editors. If you find yourself calling applyPlugin often, consider whether it'd be better to just add the plugin to the entire test suite, so that it can be built up front.

    Type Parameters

    • B extends Object
    • O extends unknown = unknown

    Parameters

    Returns Test<Ext & B, Opts & O> & Ext & B

  • Return true if the specified plugin is loaded. Asserts that the test object in question implements the return value of the plugin.

    Type Parameters

    • T extends unknown = any

    Parameters

    • plugin: ((t, opts?) => T)
        • (t, opts?): T
        • Parameters

          • t: any
          • Optional opts: any

          Returns T

    Returns this is TestBase & T

Spies, Mocks, and Fixtures

  • get testdirName(): string
  • The name of the folder that this test will use with @tapjs/fixture!index.TestFixtures#testdir.

    By default, it uses a folder name based on the name of the test file and subtest, within .tap/fixtures in the root of the project.

    Returns string

  • set testdirName(td): void
  • Parameters

    • td: string

    Returns void

  • Intercept calls to a method to track the arguments, call site, and return/throw status, and replace the implementation.

    By default, the method is set to a no-op. To retain the method behavior, pass the current value of the method as the third argument. For example:

    const results = t.capture(obj, 'foo', obj.foo)
    

    Automatically restores at t.teardown() if the @tapjs/after plugin is not disabled. Otherwise, it is important to call the restore() method on the returned function when you are done capturing.

    Type Parameters

    • T extends {}
    • M extends string | number | symbol

    Parameters

    • obj: T
    • method: M
    • Optional impl: ((this, ...a) => any)
        • (this, ...a): any
        • Parameters

          • this: T
          • Rest ...a: any[]

          Returns any

    Returns CaptureResultsMethod<T, M, T[M]>

  • Just wrap the function and return it. Does not have any logic to restore, since it's not actually modifying anything. The results hang off the function as the 'calls' property.

    The added fn.args() method will return an array of the arguments passed to each call since the last time it was inspected.

    Type Parameters

    • F extends ((this, ...a) => any)

    Parameters

    • original: F

    Returns F & {
        args: (() => TupleUnion<FilterUnknown<OverloadParamsTuple<F>>>[]);
        calls: CaptureResult<F>[];
    }

  • Convenience method to create a mock from an existing object by overriding some (possibly deeply nested) methods or properties.

    Example:

    import * as fs from 'node:fs'
    const mockedThing = t.mockRequire('./module.js', t.createMock(
    { fs },
    { fs: { statSync: myMockedStatSync }}
    )

    This can also appear anywhere in the object hierarchy, which may be more convenient in some cases:

    import * as blah from '@long-name/blah-api'
    const mockedThing = t.mockRequire('./module.js', {
    fs: t.createMock(fs, { statSync: myMockedStatSync }),
    child_process: t.createMock(child_process, { spawn: mockSpawn }),
    '@long-name/blah-api': t.createMock(blah, {
    some: {
    nested: {
    prop: true
    }
    }
    })
    })

    To remove a property, set it as undefined in the override.

    Type Parameters

    • B extends any[] | {
          [k: PropertyKey]: any;
      }
    • O extends any[] | {
          [k: string]: any;
      }

    Parameters

    • bases: B
    • overrides: O

    Returns MockedObject<B, O>

  • Intercept and track object property sets and gets.

    If a PropertyDescriptor is set, then it will be used as the replacement value. Otherwise, the original descriptor will be used.

    If the strictMode param is set, then attempts to write to read-only properties will throw an error.

    Type Parameters

    • T extends object

    Parameters

    • obj: T
    • prop: keyof T
    • Optional desc: PropertyDescriptor
    • Optional strictMode: boolean

    Returns InterceptResultsMethod

  • Deprecated alias for @tapjs/mock!index.TapMock#mockRequire

    Prints a warning to stderr the first time it used, otherwise identical.

    Type Parameters

    • T = any

    Parameters

    • module: string
    • Optional mocks: {
          [k: string]: any;
      }
      • [k: string]: any

    Returns T

    Deprecated

  • Load the supplied module asynchronously using import(), replacing any of the referenced modules with the mocks provided.

    Works with either ESM or CommonJS modules, but as with import() of CommonJS modules, the module.exports value will be set as the default property on the resolved object, making @tapjs/mock!index.TapMock#mockRequire somewhat more intuitive in those cases.

    For type info, cast using as typeof import(...) or use the type parameter, as TypeScript lacks a way to infer imports dynamically.

    For example:

    const myThing = await t.mockImport<
    typeof import('../my-thing.js')
    >('../my-thing.js', {
    some: { tricky: 'mocks' },
    })

    Type Parameters

    • T = any

    Parameters

    • module: string
    • Optional mocks: Record<string, any>

    Returns Promise<T>

  • Load the supplied module synchronously using require(), replacing any of the referenced modules with the mocks provided.

    Only works with CommonJS modules.

    For type info, cast using as typeof import(...) or use the type parameter, as TypeScript lacks a way to infer imports dynamically.

    For example:

    const myThing = t.mockRequire<
    typeof import('../my-thing.js')
    >('../my-thing.js', {
    some: { tricky: 'mocks' },
    })

    Type Parameters

    • T = any

    Parameters

    • module: string
    • Optional mocks: Record<string, any>

    Returns T

  • Create a test directory, optionally filling it up with contents

    If the @tapjs/after plugin is loaded, the testdir will be automatically deleted at the end of the test.

    To not delete the directory after the test, use the saveFixture: true option when creating the test, or specify --save-fixture on the command line or in the tap configuration.

    Parameters

    Returns string

  • Unwind the mocks and free up the memory at the end of the test.

    Called automatically if the @tapjs/after plugin is not disabled.

    Returns void

Subtest Methods

  • Spawn a child process and parse its standard output as a subtest

    Parameters

    • cmd: string

    Returns PromiseWithSpawn

  • Parameters

    • cmd: string
    • options: SpawnOpts
    • Optional name: string

    Returns PromiseWithSpawn

  • Parameters

    • cmd: string
    • args: string | string[]
    • Optional name: string

    Returns PromiseWithSpawn

  • Parameters

    • cmd: string
    • args: string | string[]
    • options: SpawnOpts
    • Optional name: string

    Returns PromiseWithSpawn

  • Parse stdin as the only tap stream (ie, not as a child test) If used, then no other subtests or assertions are allowed.

    Type Parameters

    Parameters

    • Optional extra: T & {
          tapStream?: Readable | Minipass<string | Buffer, ContiguousData, Events<string | Buffer>>;
      }

    Returns void

  • Internal

    Mount a subtest, using this Test object as a harness. Exposed so that it can be used by some builtin plugins, but perhaps the least convenient way imaginable to create subtests. Just use t.test() to do that, it's much easier.

    Type Parameters

    Parameters

    • Class: (new (options) => T)
        • new (options): T
        • Parameters

          • options: O

          Returns T

    • Optional extra: TestBaseOpts | O
    • Optional caller: ((...a) => unknown)
        • (...a): unknown
        • Parameters

          • Rest ...a: any[]

          Returns unknown

    Returns PromiseWithSubtest<T>

  • Start a Node Worker thread and parse its standard output as a child test

    Parameters

    • filename: string

    Returns PromiseWithWorker

  • Parameters

    • filename: string
    • Optional name: string

    Returns PromiseWithWorker

  • Parameters

    • filename: string
    • options: WorkerOpts
    • Optional name: string

    Returns PromiseWithWorker

Test Lifecycle Management

jobs: number

The number of subtests to run in parallel, if allowed

  • Runs the supplied function after the test is completely finished, and before the next test starts.

    Parameters

    • fn: (() => any)
        • (): any
        • Returns any

    Returns void

  • Run the supplied function after every child test, and any of those child tests' children, and so on.

    The test that has just completed is passed in as an argument to the function. Note that at this point, the test is fully ended, so attempting to call assertion methods on it will raise an error.

    Parameters

    Returns void

  • Just run the supplied function right away, but do not run any child tests until it has completed.

    This is handy when some setup may require asynchronous actions, and tests should wait until after it completes.

    Parameters

    • fn: (() => any)
        • (): any
        • Returns any

    Returns void

  • Run the supplied function before any child tests, and all of their children, and so on.

    The test about to run is an argument to the function. While its test method has not yet run, it is safe to call test methods on it, but note that this may potentially be confusing if for example you call t.plan() and this conflicts with the t.plan() called in the test method.

    Parameters

    Returns void

  • Explicitly mark the test as completed, outputting the TAP plan line if needed.

    This is not required to be called if the test function returns a promise, or if a plan is explicitly declared and eventually fulfilled.

    Returns this

  • Set the amount of time in milliseconds before this test is considered a timeout. The time is counted from right now, so for example, repeatedly calling t.setTimeout(100) can keep it going indefinitely, as long as you call it more often than every 100ms.

    Calling setTimeout(0) will remove the timer and allow the test to run indefinitely.

    Parameters

    • n: number

    Returns void

Test Reflection

bailedOut: string | boolean

True if this test emitted a bailout

count: number

The count of all assertions made directly on this test.

counts: Counts

The count of all assertions that this stream emitted

errors: TapError[]

Unrecoverable TAP protocol errors in the stream

hrtime: bigint

High resolution time in ns that this test took to complete.

isMainThread: boolean

True if in the main thread. False when running in a worker thread spawned by t.worker

lists: Lists

Lists of todo, skip, and failure test points. If passes: true is set in the options, then passing test points will also be tracked.

name: string

the name of this test

results?: FinalResults

Set on completion. The results of the test run.

Attached when the Test class is instantiated from a TestBase, as a reference to the final plugged-in Test instance. If TestBase is used directly (outside the context of a plugin) or during plugin setup time, this will be undefined, so watch out.

time: number

Amount of time in milliseconds that this test took to complete.

  • get printedOutput(): boolean
  • True if the test has printed some output of any kind

    Returns boolean

Generated using TypeDoc