Interface that is the assembled result of every loaded plugin.

This is extended into an interface because otherwise the code hinting is overwhelmingly extravagant.

interface BuiltPlugins {
    isMainThread: boolean;
    writeSnapshot: boolean;
    cleanSnapshot: undefined | ((snapshotData: string) => string);
    compareOptions: CompareOptions;
    formatSnapshot: undefined | ((obj: any) => any);
    runOnly: boolean;
    saveFixture: boolean;
    snapshotFile: string;
    testdirName: string;
    get workerData(): any;
    after(fn: (() => any)): void;
    afterEach(fn: ((t: Test<BuiltPlugins, TestOpts>) => any)): void;
    before(fn: (() => any)): void;
    beforeEach(fn: ((t: Test<BuiltPlugins, TestOpts>) => any)): void;
    capture<T, M>(obj: T, method: M, impl?: ((this: T, ...a: any[]) => any)): CaptureResultsMethod<T, M, T[M]>;
    captureFn<F>(original: F): F & {
        args: (() => TupleUnion<FilterUnknown<OverloadParamsTuple<F>>>[]);
        calls: CaptureResult<F>[];
    };
    chdir(dir: string): void;
    createMock<B, O>(bases: B, overrides: O): MockedObject<B, O>;
    doesNotThrow(fn: Function | (() => any), ...__namedParameters: MessageExtra): boolean | Error;
    emits(emitter: EventEmitter<DefaultEventMap> | EventTarget, event: string, ...__namedParameters: MessageExtra): Promise<void>;
    equal<T>(found: any, wanted: T, ...__namedParameters: MessageExtra): found is T;
    error(er: unknown, ...__namedParameters: MessageExtra): boolean;
    fixture<T>(type: T, content: FixtureContent<T>): Fixture<T>;
    has(found: any, wanted: any, ...__namedParameters: MessageExtra): boolean;
    hasOwnProp<T>(found: T, wanted: string | number | symbol, ...__namedParameters: MessageExtra): boolean;
    hasOwnProps<T>(found: T, wanted: Iterable<string | number | symbol>, ...__namedParameters: MessageExtra): boolean;
    hasOwnPropsOnly<T>(found: T, wanted: Iterable<string | number | symbol>, ...__namedParameters: MessageExtra): boolean;
    hasProp<T>(found: T, wanted: string | number | symbol, ...__namedParameters: MessageExtra): boolean;
    hasProps<T>(found: T, wanted: Iterable<string | number | symbol>, ...__namedParameters: MessageExtra): boolean;
    hasStrict(found: any, wanted: any, ...__namedParameters: MessageExtra): boolean;
    intercept<T>(obj: T, prop: keyof T, desc?: PropertyDescriptor, strictMode?: boolean): InterceptResultsMethod;
    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>(module: string, mocks?: {
        [k: string]: any;
    }): T;
    mockAll(mocks?: null | Record<string, any>): Record<string, any>;
    mockImport<T>(module: string, mocks?: Record<string, any>): Promise<T>;
    mockRequire<T>(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;
    ok(obj: any, ...__namedParameters: MessageExtra): boolean;
    only(name: string, extra: TestOpts, cb: ((t: Test<BuiltPlugins, TestOpts>) => any)): PromiseWithSubtest<Test<BuiltPlugins, TestOpts>>;
    only(name: string, cb: ((t: Test<BuiltPlugins, TestOpts>) => any)): PromiseWithSubtest<Test<BuiltPlugins, TestOpts>>;
    only(extra: TestOpts, cb: ((t: Test<BuiltPlugins, TestOpts>) => any)): PromiseWithSubtest<Test<BuiltPlugins, TestOpts>>;
    only(cb: ((t: Test<BuiltPlugins, TestOpts>) => any)): PromiseWithSubtest<Test<BuiltPlugins, TestOpts>>;
    rejects<T>(fnOrPromise: (() => Promise<T>) | Promise<T>, ...__namedParameters: ThrowsArgs): Promise<boolean | Error>;
    resolveMatch<T>(fnOrPromise: Promise<T> | (() => Promise<T>), wanted: any, ...__namedParameters: MessageExtra): Promise<boolean>;
    resolveMatchSnapshot<T>(fnOrPromise: Promise<T> | (() => Promise<T>), ...__namedParameters: MessageExtra): Promise<boolean>;
    resolves<T>(fnOrPromise: Promise<T> | (() => Promise<T>), ...__namedParameters: MessageExtra): Promise<boolean | Error>;
    same(found: any, wanted: any, ...__namedParameters: MessageExtra): boolean;
    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;
    strictNotSame(found: any, doNotWant: any, ...__namedParameters: MessageExtra): boolean;
    strictSame<T>(found: any, wanted: T, ...__namedParameters: MessageExtra): found is T;
    teardown(fn: (() => any)): void;
    testdir(content?: FixtureDirContent): string;
    throws(fn: Function | (() => any), ...__namedParameters: ThrowsArgs): boolean | Error;
    type(obj: any, klass: string | Function, ...__namedParameters: MessageExtra): boolean;
    unmock(): void;
    worker(filename: string): PromiseWithWorker;
    worker(filename: string, name?: string): PromiseWithWorker;
    worker(filename: string, options: WorkerOpts, name?: string): PromiseWithWorker;
}

Hierarchy (view full)

Properties

writeSnapshot: boolean

Accessors

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

    Returns void

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

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

    Returns void

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

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

    Parameters

    • dir: string

    Returns void

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

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

    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

    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

    • 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

    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

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

  • Parameters

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

    Returns PromiseWithSpawn

  • Parameters

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

    Returns PromiseWithSpawn

  • Parameters

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

    Returns PromiseWithSpawn

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

    Parameters

    • filename: string

    Returns PromiseWithWorker

  • Parameters

    • filename: string
    • Optionalname: string

    Returns PromiseWithWorker

  • Parameters

    • filename: string
    • options: WorkerOpts
    • Optionalname: string

    Returns PromiseWithWorker

Test Lifecycle Management

  • 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

Test Reflection

isMainThread: boolean

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