Node TAP
    Preparing search index...

    Interface TAP

    This is a singleton subclass of the @tapjs/test!index.Test base class.

    Instantiate it by calling the exported @tapjs/core!tap.tap method.

    It has all of the same plugins, fields, properties etc of a "normal" Test object, but with some additional characteristics to make it suitable for use as the root test runner.

    • The @tapjs/core!tap.TAP#register method will hook onto the process object, to set the exit code to 1 if there are test failures, and ignore any EPIPE errors that happen on stdout. (This is quite common in cases where a test aborts, and then attempts to write more data.)

    • A brief summary is printed at the end of the test run.

    • If piped to stdout, then this.register() will be called automatically.

    • If not piped anywhere else, the first time it writes any data, it will begin piping to stdout.

    • Options are set based on relevant environment variables, rather than taking an options object, since in normal cases, it will be instantiated automatically before any user code is run.

    • The test will automatically implicitly end when the process exits. If there are any unfinished tests at this time, they will be emitted as failures.

    • If a teardown function is added, then the test will automatically implicitly end if it is idle for 3 consecutive setTimeout deferrals. This is a bit of a kludge, but it allows tests to run servers or other things that would prevent a graceful process exit, and close them down in a teardown function.

    • Lastly, since test files are often spawned by the runner using t.spawn(), this class listens for the timeout signal, and attempts to print diagnostic information about currently active handles and requests, as these are usually the cause of a test hanging indefinitely.

    interface TAP {
        "[ABORTED]": boolean;
        "[ASYNC]": boolean;
        "[BUFFER]": string[];
        "[BUFFERLENGTH]": number;
        "[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;
        activeSubtests: Set<Base<TapBaseEvents>>;
        bail: boolean;
        bailedOut: string | boolean;
        buffered: boolean;
        cb?: (...args: any[]) => any;
        childId: number;
        count: number;
        counts: Counts;
        debug: (...args: any[]) => void;
        deferred?: Deferred<FinalResults>;
        diagnostic: null | boolean;
        donePromise?: Promise<any> & { tapAbortPromise?: () => void };
        ended: boolean;
        errors: TapError[];
        hook: TapWrap;
        hookDomain: Domain;
        hrtime: bigint;
        indent: string;
        isMainThread: boolean;
        jobs: number;
        lists: Lists;
        name: string;
        nestingLevel: number;
        omitVersion: boolean;
        options: TestBaseOpts;
        output: string;
        parent?: TestBase;
        parser: Parser;
        pool: Set<Base<TapBaseEvents>>;
        preserveWhitespace: boolean;
        queue: QueueEntry[];
        readable: boolean;
        readyToProcess: boolean;
        results?: FinalResults;
        silent: boolean;
        start: bigint;
        strict: boolean;
        subtests: Base<TapBaseEvents>[];
        t: Test;
        time: number;
        timedOut: boolean;
        timer?: Timeout;
        writable: boolean;
        writeSnapshot: boolean;
        get aborted(): boolean;
        set aborted(_: boolean): void;
        get assertTotals(): Counts;
        get async(): boolean;
        set async(a: boolean): void;
        get bufferLength(): number;
        get cleanSnapshot(): undefined | ((snapshotData: string) => string);
        set cleanSnapshot(
            clean: undefined | ((snapshotData: string) => string),
        ): void;
        get compareOptions(): CompareOptions;
        set compareOptions(cmt: CompareOptions): void;
        get context(): any;
        set context(c: any): void;
        get currentAssert(): undefined | Function | ((...a: any[]) => any);
        set currentAssert(fn: undefined | Function | ((...a: any[]) => any)): void;
        get destroyed(): boolean;
        get emittedEnd(): boolean;
        get encoding(): null | BufferEncoding;
        set encoding(_enc: null | BufferEncoding): void;
        get flowing(): boolean;
        get formatSnapshot(): undefined | ((obj: any) => any);
        set formatSnapshot(format: undefined | ((obj: any) => any)): void;
        get fullname(): string;
        get idle(): boolean;
        get objectMode(): boolean;
        set objectMode(_om: boolean): void;
        get occupied(): boolean;
        get paused(): boolean;
        get plugins(): TapPlugin<any, Opts>[];
        get pluginSignature(): string;
        get printedOutput(): boolean;
        get printedResult(): boolean;
        get registered(): boolean;
        get runOnly(): boolean;
        set runOnly(o: boolean): void;
        get saveFixture(): boolean;
        set saveFixture(save: boolean): void;
        get snapshotFile(): string;
        set snapshotFile(f: string | URL): void;
        get started(): boolean;
        get streamWritable(): boolean;
        get testdirName(): string;
        set testdirName(td: string): void;
        get workerData(): any;
        "[ABORT]"(): void;
        "[asyncIterator]"(): AsyncGenerator<string, void, void>;
        "[BUFFERPUSH]"(chunk: string): void;
        "[BUFFERSHIFT]"(): string;
        "[captureRejectionSymbol]"?<K>(
            error: Error,
            event: string | symbol,
            ...args: AnyRest,
        ): void;
        "[EMITDATA]"(data: string): boolean;
        "[EMITEND]"(): boolean;
        "[EMITEND2]"(): boolean;
        "[FLUSH]"(noDrain?: boolean): void;
        "[FLUSHCHUNK]"(chunk: string): boolean;
        "[iterator]"(): Generator<string, void, void>;
        "[MAYBE_EMIT_END]"(): void;
        "[READ]"(n: null | number, chunk: string): string;
        "[RESUME]"(): void;
        addListener<Event extends keyof TestBaseEvents>(
            ev: Event,
            handler: (...args: TestBaseEvents[Event]) => any,
        ): this;
        after(fn: () => any): void;
        afterEach(fn: (t: Test) => any): void;
        applyPlugin<B extends Object, O extends unknown = unknown>(
            plugin: TapPlugin<B, O>,
        ): Test<
            BuiltPlugins & B,
            TestBaseOpts & AssertOptions & FilterOptions & TestFixturesOptions & SnapshotOptions & O,
        > & BuiltPlugins & B;
        bailout(message?: string): void;
        before(fn: () => any): void;
        beforeEach(fn: (t: Test) => any): void;
        capture<T extends {}, M extends string | number | symbol>(
            obj: T,
            method: M,
            impl?: (this: T, ...a: any[]) => any,
        ): CaptureResultsMethod<T, M>;
        captureFn<F extends (this: any, ...a: any[]) => any>(
            original: F,
        ): F & {
            args: () => TupleUnion<FilterUnknown<OverloadParamsTuple<F>>>[];
            calls: CaptureResult<F>[];
        };
        chdir(dir: string): void;
        collect(): Promise<string[] & { dataLength: number }>;
        comment(...args: any[]): void;
        concat(): Promise<string>;
        createMock<
            B extends any[]
            | { [k: string | number | symbol]: any },
            O extends any[] | { [k: string]: any },
        >(
            bases: B,
            overrides: O,
        ): MockedObject<B, O>;
        destroy(er?: unknown): this;
        doesNotThrow(
            fn: Function | (() => any),
            ...__namedParameters: MessageExtra,
        ): boolean | Error;
        emit<Event extends keyof TestBaseEvents>(
            ev: Event,
            ...data: TestBaseEvents[Event],
        ): boolean;
        emits(
            emitter: EventEmitter<DefaultEventMap> | EventTarget,
            event: string,
            ...__namedParameters: MessageExtra,
        ): Promise<void>;
        end(): this;
        endAll(sub?: boolean): void;
        equal<T extends unknown>(
            found: any,
            wanted: T,
            ...__namedParameters: MessageExtra,
        ): found is T;
        error(er: unknown, ...__namedParameters: MessageExtra): boolean;
        eventNames(): (string | symbol)[];
        fail(...__namedParameters: MessageExtra): boolean;
        fixture<T extends FixtureType>(
            type: T,
            content: FixtureContent<T>,
        ): Fixture<T>;
        getMaxListeners(): number;
        has(found: any, wanted: any, ...__namedParameters: MessageExtra): boolean;
        hasOwnProp<T extends {}>(
            found: T,
            wanted: string | number | symbol,
            ...__namedParameters: MessageExtra,
        ): boolean;
        hasOwnProps<T extends {}>(
            found: T,
            wanted: Iterable<string | number | symbol>,
            ...__namedParameters: MessageExtra,
        ): boolean;
        hasOwnPropsOnly<T extends {}>(
            found: T,
            wanted: Iterable<string | number | symbol>,
            ...__namedParameters: MessageExtra,
        ): boolean;
        hasProp<T extends {}>(
            found: T,
            wanted: string | number | symbol,
            ...__namedParameters: MessageExtra,
        ): boolean;
        hasProps<T extends {}>(
            found: T,
            wanted: Iterable<string | number | symbol>,
            ...__namedParameters: MessageExtra,
        ): boolean;
        hasStrict(
            found: any,
            wanted: any,
            ...__namedParameters: MessageExtra,
        ): boolean;
        intercept<T extends object>(
            obj: T,
            prop: keyof T,
            desc?: PropertyDescriptor,
            strictMode?: boolean,
        ): InterceptResultsMethod;
        listenerCount<K>(eventName: string | symbol, listener?: Function): number;
        listeners<K>(eventName: string | symbol): Function[];
        main(cb: () => void): void;
        match(found: any, wanted: any, ...__namedParameters: MessageExtra): boolean;
        matchOnly(
            found: any,
            wanted: any,
            ...__namedParameters: MessageExtra,
        ): boolean;
        matchOnlyStrict(
            found: any,
            wanted: any,
            ...__namedParameters: MessageExtra,
        ): boolean;
        matchSnapshot(found: any, ...__namedParameters: MessageExtra): boolean;
        matchStrict(
            found: any,
            wanted: any,
            ...__namedParameters: MessageExtra,
        ): boolean;
        mock<T = any>(module: string, mocks?: { [k: string]: any }): T;
        mockAll(mocks?: null | Record<string, any>): Record<string, any>;
        mockImport<T = any>(
            module: string,
            mocks?: Record<string, any>,
        ): Promise<T>;
        mockRequire<T = any>(module: string, mocks?: Record<string, any>): T;
        not(
            found: any,
            doNotWant: any,
            ...__namedParameters: MessageExtra,
        ): boolean;
        notHas(
            found: any,
            doNotWant: any,
            ...__namedParameters: MessageExtra,
        ): boolean;
        notHasStrict(
            found: any,
            doNotWant: any,
            ...__namedParameters: MessageExtra,
        ): boolean;
        notMatch(
            found: any,
            doNotWant: any,
            ...__namedParameters: MessageExtra,
        ): boolean;
        notMatchOnly(
            found: any,
            doNotWant: any,
            ...__namedParameters: MessageExtra,
        ): boolean;
        notMatchOnlyStrict(
            found: any,
            doNotWant: any,
            ...__namedParameters: MessageExtra,
        ): boolean;
        notMatchStrict(
            found: any,
            doNotWant: any,
            ...__namedParameters: MessageExtra,
        ): boolean;
        notOk(obj: any, ...__namedParameters: MessageExtra): boolean;
        notSame(
            found: any,
            doNotWant: any,
            ...__namedParameters: MessageExtra,
        ): boolean;
        off<Event extends keyof TestBaseEvents>(
            ev: Event,
            handler: (...args: TestBaseEvents[Event]) => any,
        ): this;
        ok(obj: any, ...__namedParameters: MessageExtra): boolean;
        on<Event extends keyof TestBaseEvents>(
            ev: Event,
            handler: (...args: TestBaseEvents[Event]) => any,
        ): this;
        onbail(reason?: string): void;
        onbeforeend(): void | Promise<void>;
        once<K>(
            eventName: string | symbol,
            listener: (...args: any[]) => void,
        ): this;
        oncomplete(results: FinalResults): void;
        ondone(): void;
        onEOF(): void | Promise<void>;
        only(
            name: string,
            extra: TestOpts,
            cb: (t: Test) => any,
        ): PromiseWithSubtest<Test<BuiltPlugins, TestOpts>>;
        only(
            name: string,
            cb: (t: Test) => any,
        ): PromiseWithSubtest<Test<BuiltPlugins, TestOpts>>;
        only(
            extra: TestOpts,
            cb: (t: Test) => any,
        ): PromiseWithSubtest<Test<BuiltPlugins, TestOpts>>;
        only(
            cb: (t: Test) => any,
        ): PromiseWithSubtest<Test<BuiltPlugins, TestOpts>>;
        pass(...__namedParameters: MessageExtra): boolean;
        passing(): boolean;
        pause(): void;
        pipe<W extends Writable>(dest: W, opts?: PipeOptions): W;
        plan(n: number, comment?: string): void;
        pluginLoaded<T extends unknown = any>(
            plugin: (t: any, opts?: any) => T,
        ): this is TestBase & T;
        pragma(set: { [k: string]: boolean }): void;
        prependListener<K>(
            eventName: string | symbol,
            listener: (...args: any[]) => void,
        ): this;
        prependOnceListener<K>(
            eventName: string | symbol,
            listener: (...args: any[]) => void,
        ): this;
        promise(): Promise<void>;
        rawListeners<K>(eventName: string | symbol): Function[];
        read(n?: null | number): null | string;
        register(): void;
        rejects<T extends unknown = any>(
            fnOrPromise: (() => Promise<T>) | Promise<T>,
            ...__namedParameters: ThrowsArgs,
        ): Promise<boolean | Error>;
        removeAllListeners<Event extends keyof TestBaseEvents>(ev?: Event): this;
        removeListener<Event extends keyof TestBaseEvents>(
            ev: Event,
            handler: (...args: TestBaseEvents[Event]) => any,
        ): this;
        resolveMatch<T extends unknown = any>(
            fnOrPromise: Promise<T> | (() => Promise<T>),
            wanted: any,
            ...__namedParameters: MessageExtra,
        ): Promise<boolean>;
        resolveMatchSnapshot<T extends unknown = any>(
            fnOrPromise: Promise<T> | (() => Promise<T>),
            ...__namedParameters: MessageExtra,
        ): Promise<boolean>;
        resolves<T extends unknown = any>(
            fnOrPromise: Promise<T> | (() => Promise<T>),
            ...__namedParameters: MessageExtra,
        ): Promise<boolean | Error>;
        resume(): void;
        runMain(cb: () => void): void;
        same(found: any, wanted: any, ...__namedParameters: MessageExtra): boolean;
        setEncoding(_enc: Encoding): void;
        setMaxListeners(n: number): this;
        setTimeout(n: number): void;
        shouldSkipChild<O extends BaseOpts>(
            extra: TestBaseOpts | BaseOpts | O,
        ): boolean;
        skip(
            name: string,
            extra: TestOpts,
            cb: (t: Test<BuiltPlugins, TestOpts> & BuiltPlugins) => any,
        ): PromiseWithSubtest<Test<BuiltPlugins, TestOpts> & BuiltPlugins>;
        skip(
            name: string,
            cb: (t: Test<BuiltPlugins, TestOpts> & BuiltPlugins) => any,
        ): PromiseWithSubtest<Test<BuiltPlugins, TestOpts> & BuiltPlugins>;
        skip(
            extra: TestOpts,
            cb: (t: Test<BuiltPlugins, TestOpts> & BuiltPlugins) => any,
        ): PromiseWithSubtest<Test<BuiltPlugins, TestOpts> & BuiltPlugins>;
        skip(
            cb: (t: Test<BuiltPlugins, TestOpts> & BuiltPlugins) => any,
        ): PromiseWithSubtest<Test<BuiltPlugins, TestOpts> & BuiltPlugins>;
        spawn(cmd: string): PromiseWithSpawn;
        spawn(cmd: string, options: SpawnOpts, name?: string): PromiseWithSpawn;
        spawn(
            cmd: string,
            args: string | string[],
            name?: string,
        ): PromiseWithSpawn;
        spawn(
            cmd: string,
            args: string | string[],
            options: SpawnOpts,
            name?: string,
        ): PromiseWithSpawn;
        stdin(): PromiseWithStdin;
        stdin(name: string): PromiseWithStdin;
        stdin(name: string, extra: StdinOpts): PromiseWithStdin;
        stdin(extra: StdinOpts): PromiseWithStdin;
        stdinOnly<T extends BaseOpts>(
            extra?: T & {
                tapStream?:
                    | Readable
                    | Minipass<
                        string
                        | Buffer<ArrayBufferLike>,
                        ContiguousData,
                        Events<string | Buffer<ArrayBufferLike>>,
                    >;
            },
        ): void;
        strictNotSame(
            found: any,
            doNotWant: any,
            ...__namedParameters: MessageExtra,
        ): boolean;
        strictSame<T extends unknown>(
            found: any,
            wanted: T,
            ...__namedParameters: MessageExtra,
        ): found is T;
        sub<T extends Base<TapBaseEvents>, O extends BaseOpts>(
            Class: new (options: O) => T,
            extra?: TestBaseOpts | O,
            caller?: (...a: any[]) => unknown,
        ): PromiseWithSubtest<T>;
        teardown(fn: () => any): void;
        test(
            name: string,
            extra: TestOpts,
            cb: (t: Test<BuiltPlugins, TestOpts> & BuiltPlugins) => any,
        ): PromiseWithSubtest<Test<BuiltPlugins, TestOpts> & BuiltPlugins>;
        test(
            name: string,
            cb: (t: Test<BuiltPlugins, TestOpts> & BuiltPlugins) => any,
        ): PromiseWithSubtest<Test<BuiltPlugins, TestOpts> & BuiltPlugins>;
        test(
            extra: TestOpts,
            cb: (t: Test<BuiltPlugins, TestOpts> & BuiltPlugins) => any,
        ): PromiseWithSubtest<Test<BuiltPlugins, TestOpts> & BuiltPlugins>;
        test(
            cb: (t: Test<BuiltPlugins, TestOpts> & BuiltPlugins) => any,
        ): PromiseWithSubtest<Test<BuiltPlugins, TestOpts> & BuiltPlugins>;
        testdir(content?: FixtureDirContent): string;
        threw(er: any, extra?: Extra, proxy?: boolean): undefined | void | Extra;
        throws(
            fn: Function | (() => any),
            ...__namedParameters: ThrowsArgs,
        ): boolean | Error;
        timeout(options?: { expired?: string; signal?: null | Signals }): void;
        todo(
            name: string,
            extra: TestOpts,
            cb: (t: Test<BuiltPlugins, TestOpts> & BuiltPlugins) => any,
        ): PromiseWithSubtest<Test<BuiltPlugins, TestOpts> & BuiltPlugins>;
        todo(
            name: string,
            cb: (t: Test<BuiltPlugins, TestOpts> & BuiltPlugins) => any,
        ): PromiseWithSubtest<Test<BuiltPlugins, TestOpts> & BuiltPlugins>;
        todo(
            extra: TestOpts,
            cb: (t: Test<BuiltPlugins, TestOpts> & BuiltPlugins) => any,
        ): PromiseWithSubtest<Test<BuiltPlugins, TestOpts> & BuiltPlugins>;
        todo(
            cb: (t: Test<BuiltPlugins, TestOpts> & BuiltPlugins) => any,
        ): PromiseWithSubtest<Test<BuiltPlugins, TestOpts> & BuiltPlugins>;
        type(
            obj: any,
            klass: string | Function,
            ...__namedParameters: MessageExtra,
        ): boolean;
        unmock(): void;
        unpipe<W extends Writable>(dest: W): void;
        waitOn(
            promise: Promise<any>,
            cb?: (w: Waiter) => any,
            expectReject?: boolean,
        ): Promise<void>;
        worker(filename: string): PromiseWithWorker;
        worker(filename: string, name?: string): PromiseWithWorker;
        worker(
            filename: string,
            options: WorkerOpts,
            name?: string,
        ): PromiseWithWorker;
        write(chunk: string): boolean;
    }

    Hierarchy (View Summary)

    Index

    Properties

    Accessors

    Methods

    Assertion Methods

    Internal Machinery

    Plugin Management

    Spies, Mocks, and Fixtures

    Subtest Methods

    Test Lifecycle Management

    Test Reflection

    Properties

    "[ABORTED]": boolean
    "[ASYNC]": boolean
    "[BUFFER]": string[]
    "[BUFFERLENGTH]": number
    "[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: any[]) => void

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

    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

    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

    Accessors

    • get aborted(): boolean

      True if the stream has been aborted.

      Returns boolean

    • set aborted(_: boolean): 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: boolean): 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) => 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) => string)

    • set cleanSnapshot(clean: undefined | ((snapshotData: string) => string)): void

      Parameters

      • clean: undefined | ((snapshotData: string) => 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: CompareOptions): 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: null | BufferEncoding): void

      Parameters

      • _enc: null | BufferEncoding

      Returns void

      • 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) => 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) => any)

    • set formatSnapshot(format: undefined | ((obj: any) => any)): void

      Parameters

      • format: undefined | ((obj: any) => 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: boolean): void

      Parameters

      • _om: boolean

      Returns void

      • 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: boolean): void

      Parameters

      • o: boolean

      Returns void

    • get saveFixture(): boolean

      Returns boolean

    • set saveFixture(save: boolean): 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: string | URL): 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

    Methods

    • Returns void

    • Asynchronous for await of iteration.

      This will continue emitting all chunks until the stream terminates.

      Returns AsyncGenerator<string, void, void>

    • Parameters

      • chunk: string

      Returns void

    • Returns string

    • Type Parameters

      • K

      Parameters

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

      Returns void

    • Parameters

      • data: string

      Returns boolean

    • Returns boolean

    • Returns boolean

    • Parameters

      • OptionalnoDrain: boolean

      Returns void

    • Parameters

      • chunk: string

      Returns boolean

    • 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>

    • Returns void

    • Parameters

      • n: null | number
      • chunk: string

      Returns string

    • Returns void

    • Change the working directory, for the context of a single test.

      Parameters

      • dir: string

      Returns 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

      • ...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

      • Optionaler: 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)[]

      v6.0.0

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

      Returns number

      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

      • Optionallistener: Function

        The event handler function

      Returns number

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

      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

      • Optionalmocks: 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-time listener 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. The emitter.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: any[]) => void

        The callback function

      Returns this

      v0.3.0

    • Pause the stream

      Returns void

    • Just the normal Minipass.pipe method, but automatically registers if the destination is stdout.

      Type Parameters

      • W extends Writable

      Parameters

      • dest: W
      • Optionalopts: 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 }

      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 eventName and 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: any[]) => void

        The callback function

      Returns this

      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: any[]) => void

        The callback function

      Returns this

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

      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

      • Optionaln: null | number

      Returns null | string

    • register this tap instance as being in charge of the current process ignore epipe errors, set exit code, etc.

      Happens automatically if piped to stdout.

      Returns void

    • 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

      • 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 to Infinity (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

      v0.3.5

    • Similar to the normal @tapjs/core!test-base.TestBase#timeout, but with the added feature that it will kill the process with SIGALRM if it has been registered, and will decorate the diagnostics with some information about currently running handles and requests, as these may be the reason the process is not gracefully closing in time.

      The root test runner will time out if the process receives a SIGALRM signal, or if it receives a timeout message via IPC or worker thread channel.

      Parameters

      • Optionaloptions: { expired?: string; signal?: null | Signals }

      Returns void

    • 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

    • Just the normal Minipass.write method, but automatically pipes to stdout if not piped anywhere else.

      Parameters

      • chunk: string

      Returns boolean

    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)
      • ...__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
      • ...__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

      Returns boolean

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

      Type Parameters

      • T extends {}

      Parameters

      • found: T
      • wanted: string | number | symbol
      • ...__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>
      • ...__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>
      • ...__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
      • ...__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>
      • ...__namedParameters: MessageExtra

      Returns boolean

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

      Parameters

      Returns boolean

    • Verify that the value matches the pattern provided

      Parameters

      Returns boolean

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

      Parameters

      Returns boolean

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

      Parameters

      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

      Returns boolean

    • Verify that the values are not equal

      Parameters

      Returns boolean

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

      Parameters

      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

      Returns boolean

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

      Parameters

      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

      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

      Returns boolean

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

      Parameters

      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

      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>
      • ...__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
      • ...__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>)
      • ...__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>)
      • ...__namedParameters: MessageExtra

      Returns Promise<boolean | Error>

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

      Parameters

      Returns boolean

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

      Parameters

      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)
      • ...__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
      • ...__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[]) => any

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

    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.

    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

    parent?: TestBase

    Parent test of this TAP stream

    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[]) => any)

      The current assertion being processed. Set at the start of all assertions, and used for calculating stack traces.

      Returns undefined | Function | ((...a: any[]) => any)

    • set currentAssert(fn: undefined | Function | ((...a: any[]) => any)): void

      Parameters

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

      Returns void

    • Internal

      Called when a test times out or bails out, or the process ends, marking all currently active or queued subtests as incomplete.

      No need to ever call this directly, exposed so that it can be extended by @tapjs/core!spawn.Spawn and @tapjs/core!worker.Worker, which have special behaviors that are required when a process hangs indefinitely.

      Parameters

      • Optionalsub: boolean

      Returns void

    • Internal

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

      Parameters

      • cb: () => void

      Returns 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

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

      Returns void | Promise<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
      • Optionalextra: Extra
      • Optionalproxy: boolean

      Returns undefined | void | Extra

    • 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>
      • Optionalcb: (w: Waiter) => any
      • OptionalexpectReject: boolean

      Returns Promise<void>

    Plugin Management

    • 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: any, opts?: any) => 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: string): 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
      • Optionalimpl: (this: T, ...a: any[]) => any

      Returns CaptureResultsMethod<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: any, ...a: any[]) => 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: string | number | symbol]: 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
      • Optionaldesc: PropertyDescriptor
      • OptionalstrictMode: 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
      • Optionalmocks: { [k: string]: any }

      Returns T

    • 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' },
      })

      Note: The terms "mock" and "import" are unfortunately very overloaded in the testing space. This is not "mock all imports of this module". It's "load this module, but with its imports mocked". The code of the target module is run normally, but its dependencies are injected with the supplied values, which is useful for triggering hard-to-reach error cases and other situations.

      It is also useful for just loading a fresh copy of a module in your tests, if for example your program behaves differently based on environment variables or other system settings. For example:

      t.test('windows behavior', async t => {
      t.intercept(process, 'platform', { value: 'win32' })
      const myThing = t.mockImport('../my-thing.js')
      t.equal(myThing.separator, '\\')
      })
      t.test('posix behavior', async t => {
      t.intercept(process, 'platform', { value: 'linux' })
      const myThing = t.mockImport('../my-thing.js')
      t.equal(myThing.separator, '/')
      })

      Type Parameters

      • T = any

      Parameters

      • module: string
      • Optionalmocks: 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
      • Optionalmocks: Record<string, any>

      Returns T

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

      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

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

      Parameters

      • cmd: string
      • options: SpawnOpts
      • Optionalname: string

      Returns PromiseWithSpawn

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

      Parameters

      • cmd: string
      • args: string | string[]
      • Optionalname: string

      Returns PromiseWithSpawn

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

      Parameters

      • cmd: string
      • args: string | string[]
      • options: SpawnOpts
      • Optionalname: 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

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

      Returns void

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

      Parameters

      • filename: string

      Returns PromiseWithWorker

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

      Parameters

      • filename: string
      • Optionalname: string

      Returns PromiseWithWorker

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

      Parameters

      • filename: string
      • options: WorkerOpts
      • Optionalname: 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

      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

      • fn: (t: Test) => any

      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

      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

      • fn: (t: Test) => any

      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.

    t: Test

    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