@probitas/probitas

Probitas - Scenario-based testing and workflow execution framework.

This is the main entry point for the Probitas framework. It provides a fluent API for building and executing scenario-based tests with support for:

  • Sequential steps: Define test steps that execute in order with type-safe context passing
  • Skip conditions: Conditionally skip steps or entire scenarios
  • Rich assertions: Built-in expect utilities for comprehensive assertions
  • External clients: Pre-configured clients for HTTP, databases, message queues, and more
  • Test utilities: Faker for test data, time mocking, and function spies
PackageDescription
@probitas/builderFluent API for building scenario definitions
@probitas/runnerTest execution engine with retry and concurrency
@probitas/reporterOutput formatters (list, dot, TAP, JSON)
@probitas/coreCore type definitions and utilities
@probitas/discoverScenario file discovery
@probitas/loggerUnified logging interface
@probitas/cliCommand-line interface

Core Exports

  • scenario - Factory function to create scenario builders
  • Skip - Utility to skip steps or scenarios conditionally
  • StepContext - Type representing the context passed to each step
  • client - Namespace containing all available client implementations
  • expect - Assertion utilities (from @std/expect)

Re-exported Utilities

For convenience, this module also re-exports commonly used testing utilities:

  • faker - Fake data generation from @faker-js/faker
  • FakeTime - Time mocking utilities from @std/testing/time
  • spy, stub, assertSpyCalls - Mock utilities from @std/testing/mock
  • tryOr, raise - Error handling utilities from @core/errorutil
  • outdent - Template literal tag for removing indentation

Installation

deno add jsr:@probitas/probitas

Classes

class

#FakeTime

class FakeTime

Overrides the real Date object and timer functions with fake ones that can be controlled through the fake time instance.

Note: there is no setter for the start property, as it cannot be changed after initialization.

Examples

Usage

import {
  assertSpyCalls,
  spy,
} from "@std/testing/mock";
import { FakeTime } from "@std/testing/time";

function secondInterval(cb: () => void): number {
  return setInterval(cb, 1000);
}

Deno.test("secondInterval calls callback every second and stops after being cleared", () => {
  using time = new FakeTime();

  const cb = spy();
  const intervalId = secondInterval(cb);
  assertSpyCalls(cb, 0);
  time.tick(500);
  assertSpyCalls(cb, 0);
  time.tick(500);
  assertSpyCalls(cb, 1);
  time.tick(3500);
  assertSpyCalls(cb, 4);

  clearInterval(intervalId);
  time.tick(1000);
  assertSpyCalls(cb, 4);
});
NameDescription
[Symbol.dispose]()Restores real time.
restore()Restores real time.
restoreFor()Restores real time temporarily until callback returns and resolves.
now()The number of milliseconds elapsed since the epoch (January 1, 1970 00:00:00 UTC) for the fake time.
now()Set the current time.
start()The initial number of milliseconds elapsed since the epoch (January 1, 1970 00:00:00 UTC) for the fake time.
delay()Resolves after the given number of milliseconds using real time.
runMicrotasks()Runs all pending microtasks.
tick()Adds the specified number of milliseconds to the fake time.
tickAsync()Runs all pending microtasks then adds the specified number of milliseconds to the fake time.
next()Advances time to when the next scheduled timer is due.
nextAsync()Runs all pending microtasks then advances time to when the next scheduled timer is due.
runAll()Advances time forward to the next due timer until there are no pending timers remaining.
runAllAsync()Advances time forward to the next due timer until there are no pending timers remaining.
restore()Restores time related global functions to their original state.
Constructor
new FakeTime(start?: number | string | Date | null, options?: FakeTimeOptions)

Construct a FakeTime object. This overrides the real Date object and timer functions with fake ones that can be controlled through the fake time instance.

Methods
[Symbol.dispose](): unknown

Restores real time.

static restore(): unknown

Restores real time.

static restoreFor(): unknown

Restores real time temporarily until callback returns and resolves.

now(): unknown

The number of milliseconds elapsed since the epoch (January 1, 1970 00:00:00 UTC) for the fake time.

now(): unknown

Set the current time. It will call any functions waiting to be called between the current and new fake time. If the timer callback throws, time will stop advancing forward beyond that timer.

start(): unknown

The initial number of milliseconds elapsed since the epoch (January 1, 1970 00:00:00 UTC) for the fake time.

delay(): unknown

Resolves after the given number of milliseconds using real time.

runMicrotasks(): unknown

Runs all pending microtasks.

tick(): unknown

Adds the specified number of milliseconds to the fake time. This will call any functions waiting to be called between the current and new fake time.

tickAsync(): unknown

Runs all pending microtasks then adds the specified number of milliseconds to the fake time. This will call any functions waiting to be called between the current and new fake time.

next(): unknown

Advances time to when the next scheduled timer is due. If there are no pending timers, time will not be changed.

nextAsync(): unknown

Runs all pending microtasks then advances time to when the next scheduled timer is due. If there are no pending timers, time will not be changed.

runAll(): unknown

Advances time forward to the next due timer until there are no pending timers remaining. If the timers create additional timers, they will be run too. If there is an interval, time will keep advancing forward until the interval is cleared.

runAllAsync(): unknown

Advances time forward to the next due timer until there are no pending timers remaining. If the timers create additional timers, they will be run too. If there is an interval, time will keep advancing forward until the interval is cleared. Runs all pending microtasks before each timer.

restore(): unknown

Restores time related global functions to their original state.

class

#MockError

class MockError extends Error
ExtendsError

An error related to spying on a function or instance method.

Examples

Usage

import { MockError, spy } from "@std/testing/mock";
import { assertThrows } from "@std/assert";

assertThrows(() => {
  spy({} as any, "no-such-method");
}, MockError);
Constructor
new MockError(message: string)

Construct MockError

class

#TimeError

class TimeError extends Error
ExtendsError

Represents an error when trying to execute an invalid operation on fake time, given the state fake time is in.

Examples

Usage

import { FakeTime, TimeError } from "@std/testing/time";
import { assertThrows } from "@std/assert";

assertThrows(() => {
  const time = new FakeTime();
  time.restore();
  time.restore();
}, TimeError);
Constructor
new TimeError(message: string)

Construct TimeError.

class

#UnimplementedError

class UnimplementedError extends Error
ExtendsError

Error indicating that this part is unimplemented.

Constructor
new UnimplementedError(_: unknown)
class

#UnreachableError

class UnreachableError extends Error
ExtendsError

Error indicating that this part is unreachable.

NameDescription
args
Constructor
new UnreachableError(args: unknown[])
Properties
  • readonlyargsunknown[]

Interfaces

interface

#ConstructorSpy

interface ConstructorSpy<Self = any, Args extends unknown[] = any[]>

A constructor wrapper that records all calls made to it.

NameDescription
originalThe function that is being spied on.
callsInformation about calls made to the function or instance method.
restoredWhether or not the original instance method has been restored.
restore()If spying on an instance method, this restores the original instance method.
Properties
  • original(_: Args) => unknown

    The function that is being spied on.

  • callsSpyCall<Self, Args, Self>[]

    Information about calls made to the function or instance method.

  • restoredboolean

    Whether or not the original instance method has been restored.

Methods
restore(): void

If spying on an instance method, this restores the original instance method.

interface

#DelayOptions

interface DelayOptions

Options for delay.

NameDescription
signalSignal used to abort the delay.
persistentIndicates whether the process should continue to run as long as the timer exists.
Properties
  • signal?AbortSignal

    Signal used to abort the delay.

  • persistent?boolean

    Indicates whether the process should continue to run as long as the timer exists.

interface

#ExpectedSpyCall

interface ExpectedSpyCall<Self = any, Args extends unknown[] = any[], Return = any>

Call information recorded by a spy.

NameDescription
argsArguments passed to a function when called.
selfThe instance that a method was called on.
returnedThe value that was returned by a function.
errorThe expected thrown error.
Properties
  • args?[unknown, unknown]

    Arguments passed to a function when called.

  • self?Self

    The instance that a method was called on.

  • returned?Return

    The value that was returned by a function. If you expect a promise to reject, expect error instead.

  • error?{ Class?: (_: any[]) => unknown; msgIncludes?: string }

    The expected thrown error.

interface

#FakeTimeOptions

interface FakeTimeOptions

The option for FakeTime

NameDescription
advanceRateThe rate relative to real time at which fake time is updated.
advanceFrequencyThe frequency in milliseconds at which fake time is updated.
Properties
  • advanceRatenumber

    The rate relative to real time at which fake time is updated. By default time only moves forward through calling tick or setting now. Set to 1 to have the fake time automatically tick forward at the same rate in milliseconds as real time.

  • advanceFrequency?number

    The frequency in milliseconds at which fake time is updated. If advanceRate is set, we will update the time every 10 milliseconds by default.

interface

#MethodSpy

interface MethodSpy<Self = any, Args extends unknown[] = any[], Return = any>
 extends Spy<Self, Args, Return>,
  Disposable

An instance method wrapper that records all calls made to it.

interface

#Options

interface Options
NameDescription
trimLeadingNewline
trimTrailingNewline
newlineNormalize all newlines in the template literal to this value.
Properties
  • trimLeadingNewline?boolean
  • trimTrailingNewline?boolean
  • newline?string | null

    Normalize all newlines in the template literal to this value.

    If null, newlines are left untouched.

    Newlines that get normalized are '\r\n', '\r', and '\n'.

    Newlines within interpolated values are never normalized.

    Although intended for normalizing to '\n' or '\r\n', you can also set to any string; for example ' '.

interface

#Outdent

interface Outdent
NameDescription
string()Remove indentation from a string
Methods
string(str: string): string

Remove indentation from a string

Parameters
  • strstring
interface

#Spy

interface Spy<Self = any, Args extends unknown[] = any[], Return = any>

A function or instance method wrapper that records all calls made to it.

NameDescription
originalThe function that is being spied on.
callsInformation about calls made to the function or instance method.
restoredWhether or not the original instance method has been restored.
restore()If spying on an instance method, this restores the original instance method.
Properties
  • original(this: Self, _: Args) => unknown

    The function that is being spied on.

  • callsSpyCall<Self, Args, Return>[]

    Information about calls made to the function or instance method.

  • restoredboolean

    Whether or not the original instance method has been restored.

Methods
restore(): void

If spying on an instance method, this restores the original instance method.

interface

#SpyCall

interface SpyCall<Self = any, Args extends unknown[] = any[], Return = any>

Call information recorded by a spy.

NameDescription
argsArguments passed to a function when called.
returnedThe value that was returned by a function.
errorThe error value that was thrown by a function.
selfThe instance that a method was called on.
Properties
  • argsArgs

    Arguments passed to a function when called.

  • returned?Return

    The value that was returned by a function.

  • error?Error

    The error value that was thrown by a function.

  • self?Self

    The instance that a method was called on.

interface

#Stub

interface Stub<Self = any, Args extends unknown[] = any[], Return = any> extends MethodSpy<Self, Args, Return>

An instance method replacement that records all calls made to it.

NameDescription
fakeThe function that is used instead of the original.
Properties
  • fake(this: Self, _: Args) => unknown

    The function that is used instead of the original.

Functions

function

#alter

function alter<T, E>(fn: () => unknown, alt: E): T

Alter the error of a function if an error is thrown.

Parameters
  • fn() => unknown
    • The function to execute.
  • altE
    • The value to throw if an error is thrown.
Returns

T — The result of the function.

Examples
import { assertThrows } from "@std/assert";
import { alter } from "@core/errorutil/alter";

console.log(alter(() => 1, "err2")); // 1
assertThrows(() => alter(() => { throw "err1" }, "err2"), "err2"); // "err2" is thrown
function

#alterElse

function alterElse<T, E>(
  fn: () => unknown,
  elseFn: (err: unknown) => unknown,
): T

Alter the error of a function if an error is thrown.

Parameters
  • fn() => unknown
    • The function to execute.
  • elseFn(err: unknown) => unknown
Returns

T — The result of the function.

Examples
import { assertThrows } from "@std/assert";
import { alterElse } from "@core/errorutil/alter-else";

console.log(alterElse(() => 1, () => "err")); // 1
assertThrows(() => alterElse(() => { throw "err" }, (err) => "new " + err), "new err"); // "new err" is thrown
function

#assertSpyCall

function assertSpyCall<Self, Args extends unknown[], Return>(
  spy: SpyLike<Self, Args, Return>,
  callIndex: number,
  expected?: ExpectedSpyCall<Self, Args, Return>,
): void

Asserts that a spy is called as expected.

Parameters
  • spySpyLike<Self, Args, Return>

    The spy to check

  • callIndexnumber

    The index of the call to check

  • expected?ExpectedSpyCall<Self, Args, Return>

    The expected spy call.

Examples

Usage

import { assertSpyCall, spy } from "@std/testing/mock";

const func = spy((a: number, b: number) => a + b);

func(3, 4);
func(5, 6);

// asserts each call made to the spy function.
assertSpyCall(func, 0, { args: [3, 4], returned: 7 });
assertSpyCall(func, 1, { args: [5, 6], returned: 11 });
function

#assertSpyCallArg

function assertSpyCallArg<Self, Args extends unknown[], Return, ExpectedArg>(
  spy: SpyLike<Self, Args, Return>,
  callIndex: number,
  argIndex: number,
  expected: ExpectedArg,
): ExpectedArg

Asserts that a spy is called with a specific arg as expected.

Parameters
  • spySpyLike<Self, Args, Return>

    The spy to check.

  • callIndexnumber

    The index of the call to check.

  • argIndexnumber

    The index of the arguments to check.

  • expectedExpectedArg

    The expected argument.

Returns

ExpectedArg — The actual argument.

Examples

Usage

import { assertSpyCallArg, spy } from "@std/testing/mock";

const func = spy((a: number, b: number) => a + b);

func(3, 4);
func(5, 6);

// asserts each call made to the spy function.
assertSpyCallArg(func, 0, 0, 3);
assertSpyCallArg(func, 0, 1, 4);
assertSpyCallArg(func, 1, 0, 5);
assertSpyCallArg(func, 1, 1, 6);
function

#assertSpyCallArgs(4 overloads)

function assertSpyCallArgs<Self, Args extends unknown[], Return, ExpectedArgs extends unknown[]>(
  spy: SpyLike<Self, Args, Return>,
  callIndex: number,
  expected: ExpectedArgs,
): ExpectedArgs

Asserts that an spy is called with a specific range of args as expected. If a start and end index is not provided, the expected will be compared against all args. If a start is provided without an end index, the expected will be compared against all args from the start index to the end. The end index is not included in the range of args that are compared.

Parameters
  • spySpyLike<Self, Args, Return>

    The spy to check.

  • callIndexnumber

    The index of the call to check.

  • expectedExpectedArgs

    The expected arguments.

Returns

ExpectedArgs — The actual arguments.

Examples

Usage

import { assertSpyCallArgs, spy } from "@std/testing/mock";

const func = spy((a: number, b: number) => a + b);

func(3, 4);
func(5, 6);

// asserts each call made to the spy function.
assertSpyCallArgs(func, 0, [3, 4]);
assertSpyCallArgs(func, 1, [5, 6]);
Show all 4 overloads
#1
function assertSpyCallArgs<Self, Args extends unknown[], Return, ExpectedArgs extends unknown[]>(
  spy: SpyLike<Self, Args, Return>,
  callIndex: number,
  expected: ExpectedArgs,
): ExpectedArgs

Asserts that an spy is called with a specific range of args as expected. If a start and end index is not provided, the expected will be compared against all args. If a start is provided without an end index, the expected will be compared against all args from the start index to the end. The end index is not included in the range of args that are compared.

Parameters
  • spySpyLike<Self, Args, Return>

    The spy to check.

  • callIndexnumber

    The index of the call to check.

  • expectedExpectedArgs

    The expected arguments.

Returns

ExpectedArgs — The actual arguments.

#2
function assertSpyCallArgs<Self, Args extends unknown[], Return, ExpectedArgs extends unknown[]>(
  spy: SpyLike<Self, Args, Return>,
  callIndex: number,
  argsStart: number,
  expected: ExpectedArgs,
): ExpectedArgs

Asserts that an spy is called with a specific range of args as expected. If a start and end index is not provided, the expected will be compared against all args. If a start is provided without an end index, the expected will be compared against all args from the start index to the end. The end index is not included in the range of args that are compared.

Parameters
  • spySpyLike<Self, Args, Return>

    The spy to check.

  • callIndexnumber

    The index of the call to check.

  • argsStartnumber

    The start index of the arguments to check. If not specified, it checks the arguments from the beignning.

  • expectedExpectedArgs

    The expected arguments.

Returns

ExpectedArgs — The actual arguments.

#3
function assertSpyCallArgs<Self, Args extends unknown[], Return, ExpectedArgs extends unknown[]>(
  spy: SpyLike<Self, Args, Return>,
  callIndex: number,
  argsStart: number,
  argsEnd: number,
  expected: ExpectedArgs,
): ExpectedArgs

Asserts that an spy is called with a specific range of args as expected. If a start and end index is not provided, the expected will be compared against all args. If a start is provided without an end index, the expected will be compared against all args from the start index to the end. The end index is not included in the range of args that are compared.

Parameters
  • spySpyLike<Self, Args, Return>

    The spy to check

  • callIndexnumber

    The index of the call to check

  • argsStartnumber

    The start index of the arguments to check. If not specified, it checks the arguments from the beignning.

  • argsEndnumber

    The end index of the arguments to check. If not specified, it checks the arguments until the end.

  • expectedExpectedArgs

    The expected arguments.

Returns

ExpectedArgs — The actual arguments

#4
function assertSpyCallArgs<ExpectedArgs extends unknown[], Args extends unknown[], Return, Self>(
  spy: SpyLike<Self, Args, Return>,
  callIndex: number,
  argsStart?: number | ExpectedArgs,
  argsEnd?: number | ExpectedArgs,
  expected?: ExpectedArgs,
): ExpectedArgs
Parameters
  • spySpyLike<Self, Args, Return>
  • callIndexnumber
  • argsStart?number | ExpectedArgs
  • argsEnd?number | ExpectedArgs
  • expected?ExpectedArgs
function

#assertSpyCallAsync

async function assertSpyCallAsync<Self, Args extends unknown[], Return>(
  spy: SpyLike<Self, Args, Promise<Return>>,
  callIndex: number,
  expected?: ExpectedSpyCall<Self, Args, Promise<Return> | Return>,
): Promise<void>

Asserts that an async spy is called as expected.

Parameters
  • spySpyLike<Self, Args, Promise<Return>>

    The spy to check

  • callIndexnumber

    The index of the call to check

  • expected?ExpectedSpyCall<Self, Args, Promise<Return> | Return>

    The expected spy call.

Examples

Usage

import { assertSpyCallAsync, spy } from "@std/testing/mock";

const func = spy((a: number, b: number) => new Promise((resolve) => {
  setTimeout(() => resolve(a + b), 100)
}));

await func(3, 4);
await func(5, 6);

// asserts each call made to the spy function.
await assertSpyCallAsync(func, 0, { args: [3, 4], returned: 7 });
await assertSpyCallAsync(func, 1, { args: [5, 6], returned: 11 });
function

#assertSpyCalls

function assertSpyCalls<Self, Args extends unknown[], Return>(
  spy: SpyLike<Self, Args, Return>,
  expectedCalls: number,
): void

Asserts that a spy is called as much as expected and no more.

Parameters
  • spySpyLike<Self, Args, Return>

    The spy to check

  • expectedCallsnumber

    The number of the expected calls.

Examples

Usage

import { assertSpyCalls, spy } from "@std/testing/mock";

const func = spy();

func();
func();

assertSpyCalls(func, 2);
function

#attempt

function attempt<T, E = unknown>(fn: () => unknown): Result<T, E>

Attempt to execute a function and return a Result<T, E>.

Parameters
  • fn() => unknown
    • The function to execute.
Returns

Result<T, E> — A Result<T, E> where T is the return type of the function and E is the error type.

Examples
import { attempt } from "@core/errorutil/attempt";

console.log(attempt(() => 1)); // [undefined, 1]
console.log(attempt(() => { throw "err" })); // ["err", undefined]
function

#expect(11 overloads)

function expect<T extends HttpResponse>(
  value: NotAny<T>,
): HttpResponseExpectation

Unified expect function that dispatches to the appropriate expectation function based on the type of the input object.

Parameters
  • valueNotAny<T>
Examples
import { expect } from "./expect.ts";

// Falls back to expectAnything (chainable @std/expect) for other values
expect(42).toBe(42).toBeGreaterThan(40);
expect("hello world").toContain("world");
expect({ a: 1, b: 2 }).toMatchObject({ a: 1 });
Show all 11 overloads
#1
function expect<T extends HttpResponse>(
  value: NotAny<T>,
): HttpResponseExpectation

Unified expect function that dispatches to the appropriate expectation function based on the type of the input object.

Parameters
  • valueNotAny<T>
#2
function expect<T extends ConnectRpcResponse>(
  value: NotAny<T>,
): ConnectRpcResponseExpectation
Parameters
  • valueNotAny<T>
#3
function expect<T extends GraphqlResponse>(
  value: NotAny<T>,
): GraphqlResponseExpectation
Parameters
  • valueNotAny<T>
#4
function expect<T extends SqlQueryResult>(
  value: NotAny<T>,
): SqlQueryResultExpectation
Parameters
  • valueNotAny<T>
#5
function expect<T extends DenoKvResult>(value: NotAny<T>): DenoKvExpectation<T>
Parameters
  • valueNotAny<T>
#6
function expect<T extends RedisResult>(value: NotAny<T>): RedisExpectation<T>
Parameters
  • valueNotAny<T>
#7
function expect<T extends MongoResult>(value: NotAny<T>): MongoExpectation<T>
Parameters
  • valueNotAny<T>
#8
function expect<T extends RabbitMqResult>(
  value: NotAny<T>,
): RabbitMqExpectation<T>
Parameters
  • valueNotAny<T>
#9
function expect<T extends SqsResult>(value: NotAny<T>): SqsExpectation<T>
Parameters
  • valueNotAny<T>
#10
function expect(value: any): AnythingExpectation
Parameters
  • valueany
#11
function expect(value: unknown): unknown
Parameters
  • valueunknown
function

#fromErrorObject

function fromErrorObject(obj: ErrorObject): Error

Convert an error object to an error

Parameters
function

#mockSession(3 overloads)

function mockSession(): number

Creates a session that tracks all mocks created before it's restored. If a callback is provided, it restores all mocks created within it.

Returns

number — The id of the created session.

Examples

Usage

import { mockSession, restore, stub } from "@std/testing/mock";
import { assertEquals, assertNotEquals } from "@std/assert";

const setTimeout = globalThis.setTimeout;
const id = mockSession();

stub(globalThis, "setTimeout");

assertNotEquals(globalThis.setTimeout, setTimeout);

restore(id);

assertEquals(globalThis.setTimeout, setTimeout);
Show all 3 overloads
#1
function mockSession(): number

Creates a session that tracks all mocks created before it's restored. If a callback is provided, it restores all mocks created within it.

Returns

number — The id of the created session.

#2
function mockSession<Self, Args extends unknown[], Return>(
  func: (this: Self, _: Args) => unknown,
): (this: Self, _: Args) => unknown

Creates a session that tracks all mocks created before it's restored. If a callback is provided, it restores all mocks created within it.

Parameters
  • func(this: Self, _: Args) => unknown

    The function to be used for the created session.

Returns

(this: Self, _: Args) => unknown — The function to execute the session.

#3
function mockSession<Self, Args extends unknown[], Return>(
  func?: (this: Self, _: Args) => unknown,
): number | unknown
Parameters
  • func?(this: Self, _: Args) => unknown
function

#mockSessionAsync

function mockSessionAsync<Self, Args extends unknown[], Return>(
  func: (this: Self, _: Args) => unknown,
): (this: Self, _: Args) => unknown

Creates an async session that tracks all mocks created before the promise resolves.

Parameters
  • func(this: Self, _: Args) => unknown

    The function.

Returns

(this: Self, _: Args) => unknown — The return value of the function.

Examples

Usage

import { mockSessionAsync, restore, stub } from "@std/testing/mock";
import { assertEquals, assertNotEquals } from "@std/assert";

const setTimeout = globalThis.setTimeout;
const session = mockSessionAsync(async () => {
  stub(globalThis, "setTimeout");
  assertNotEquals(globalThis.setTimeout, setTimeout);
});

await session();

assertEquals(globalThis.setTimeout, setTimeout); // stub is restored
function

#raise

function raise(err: unknown): never

Throw an error.

This is function thus can be used as an expression.

import { raise } from "@core/errorutil/raise";

const fn = () => raise(new Error("fail"));
Parameters
  • errunknown
function

#resolvesNext

function resolvesNext<Return, Self = any, Args extends unknown[] = any[]>(
  iterable: Iterable<Return | Error | Promise<Return | Error>>
| AsyncIterable<Return | Error | Promise<Return | Error>>,
): (this: Self, _: Args) => unknown

Creates a function that resolves the awaited iterable values. Any awaited iterable values that are errors will be thrown.

Parameters
  • iterableIterable<Return | Error | Promise<Return | Error>> | AsyncIterable<Return | Error | Promise<Return | Error>>

    The iterable to use

Returns

(this: Self, _: Args) => unknown — A function that resolves the awaited iterable values

Examples

Usage

import { resolvesNext } from "@std/testing/mock";
import { assertEquals, assertRejects } from "@std/assert";

const func = resolvesNext([1, 2, new Error("foo"), 3]);
assertEquals(await func(), 1);
assertEquals(await func(), 2);
assertRejects(() => func(), Error, "foo");
assertEquals(await func(), 3);
function

#restore

function restore(id?: number): void

Restores all mocks registered in the current session that have not already been restored. If an id is provided, it will restore all mocks registered in the session associed with that id that have not already been restored.

Parameters
  • id?number

    The id of the session to restore. If not provided, all mocks registered in the current session are restored.

Examples

Usage

import { mockSession, restore, stub } from "@std/testing/mock";
import { assertEquals, assertNotEquals } from "@std/assert";

const setTimeout = globalThis.setTimeout;

stub(globalThis, "setTimeout");

assertNotEquals(globalThis.setTimeout, setTimeout);

restore();

assertEquals(globalThis.setTimeout, setTimeout);
function

#returnsArg

function returnsArg<Arg, Self = any>(
  idx: number,
): (this: Self, _: Arg[]) => unknown

Creates a function that returns one of its arguments.

Parameters
  • idxnumber

    The index of the arguments to use.

Returns

(this: Self, _: Arg[]) => unknown — A function that returns one of its arguments.

Examples

Usage

import { returnsArg } from "@std/testing/mock";
import { assertEquals } from "@std/assert";

const func = returnsArg(1);
assertEquals(func(1, 2, 3), 2);
function

#returnsArgs

function returnsArgs<Args extends unknown[], Self = any>(
  _: unknown,
  end?: number,
): (this: Self, _: Args) => unknown

Creates a function that returns its arguments or a subset of them. If end is specified, it will return arguments up to but not including the end.

Parameters
  • _unknown
  • end?number

    The end index of the arguments to return.

Returns

(this: Self, _: Args) => unknown — A function that returns its arguments or a subset of them.

Examples

Usage

import { returnsArgs } from "@std/testing/mock";
import { assertEquals } from "@std/assert";

const func = returnsArgs();
assertEquals(func(1, 2, 3), [1, 2, 3]);
function

#returnsNext

function returnsNext<Return, Self = any, Args extends unknown[] = any[]>(
  values: Iterable<Return | Error>,
): (this: Self, _: Args) => unknown

Creates a function that returns the iterable values. Any iterable values that are errors will be thrown.

Parameters
  • valuesIterable<Return | Error>

    The iterable values

Returns

(this: Self, _: Args) => unknown — A function that returns the iterable values

Examples

Usage

import { returnsNext } from "@std/testing/mock";
import { assertEquals, assertThrows } from "@std/assert";

const func = returnsNext([1, 2, new Error("foo"), 3]);
assertEquals(func(), 1);
assertEquals(func(), 2);
assertThrows(() => func(), Error, "foo");
assertEquals(func(), 3);
function

#returnsThis

function returnsThis<Self = any, Args extends unknown[] = any[]>(): (this: Self, _: Args) => unknown

Creates a function that returns the instance the method was called on.

Returns

(this: Self, _: Args) => unknown — A function that returns the instance the method was called on.

Examples

Usage

import { returnsThis } from "@std/testing/mock";
import { assertEquals } from "@std/assert";

const func = returnsThis();
const obj = { func };
assertEquals(obj.func(), obj);
function

#scenario

function scenario(name: string, options?: ScenarioOptions): ScenarioBuilderInit

Create a new scenario builder with a fluent API.

This is the primary entry point for defining scenarios. It returns a builder that provides a type-safe, chainable API for constructing test scenarios.

Parameters
  • namestring
    • Human-readable scenario name (shown in test reports)
    • Optional configuration for tags, timeouts, and retry behavior
Returns

ScenarioBuilderInit — New {@linkcode ScenarioBuilderInit} instance ready for chaining

Examples

Basic scenario with type-safe step chaining

import { scenario } from "@probitas/builder";

// Mock user service for example
const createUser = (_data: { email: string }) =>
  Promise.resolve({ id: "user-123" });
const verifyEmail = (_userId: string) => Promise.resolve();

export default scenario("User Registration")
  .step("Create user", async () => {
    const user = await createUser({ email: "test@example.com" });
    return { userId: user.id };
  })
  .step("Verify email", async (ctx) => {
    // ctx.previous is typed as { userId: string }
    await verifyEmail(ctx.previous.userId);
  })
  .build();

Scenario with tags for filtering

import { scenario } from "@probitas/builder";

scenario("Payment Integration", {
  tags: ["integration", "payment", "slow"],
  stepOptions: { timeout: 60000 }  // 1 minute timeout for all steps
})
  .step("Process payment", async () => {
    return { success: true };
  })
  .build();

// Run with: probitas run -s "tag:payment"

Scenario with resources and setup

import { scenario } from "@probitas/builder";

// Mock Database for example
const Database = {
  connect: () =>
    Promise.resolve({
      rollback: () => {},
      insert: (_data: { id: number }) => {},
      query: (_sql: string) => [{ id: 1 }],
    }),
};

scenario("Database Test")
  .resource("db", async () => await Database.connect())
  .setup((ctx) => {
    // Run migrations
    return () => ctx.resources.db.rollback();
  })
  .step("Insert data", (ctx) => ctx.resources.db.insert({ id: 1 }))
  .step("Query data", (ctx) => ctx.resources.db.query("SELECT * FROM users"))
  .build();
function

#spy(5 overloads)

function spy<Self = any, Args extends unknown[] = any[], Return = undefined>(): Spy<Self, Args, Return>

Creates a spy function.

Returns

Spy<Self, Args, Return> — The spy function.

Examples

Usage

import {
  assertSpyCall,
  assertSpyCalls,
  spy,
} from "@std/testing/mock";

const func = spy();

func();
func(1);
func(2, 3);

assertSpyCalls(func, 3);

// asserts each call made to the spy function.
assertSpyCall(func, 0, { args: [] });
assertSpyCall(func, 1, { args: [1] });
assertSpyCall(func, 2, { args: [2, 3] });
Show all 5 overloads
#1
function spy<Self = any, Args extends unknown[] = any[], Return = undefined>(): Spy<Self, Args, Return>

Creates a spy function.

Returns

Spy<Self, Args, Return> — The spy function.

#2
function spy<Self, Args extends unknown[], Return>(
  func: (this: Self, _: Args) => unknown,
): Spy<Self, Args, Return>

Create a spy function with the given implementation.

Parameters
  • func(this: Self, _: Args) => unknown

    The function to wrap

Returns

Spy<Self, Args, Return> — The wrapped function.

#3
function spy<Self, Args extends unknown[]>(
  constructor: (_: Args) => unknown,
): ConstructorSpy<Self, Args>

Create a spy constructor.

Parameters
  • constructor(_: Args) => unknown

    The constructor to spy.

Returns

ConstructorSpy<Self, Args> — The wrapped constructor.

#4
function spy<Self, Prop extends keyof Self>(
  self: Self,
  property: Prop,
): MethodSpy<Self, GetParametersFromProp<Self, Prop>, GetReturnFromProp<Self, Prop>>

Wraps a instance method with a Spy.

Parameters
  • selfSelf

    The instance to spy.

  • propertyProp

    The property of the method to spy.

Returns

MethodSpy<Self, GetParametersFromProp<Self, Prop>, GetReturnFromProp<Self, Prop>> — The spy function.

#5
function spy<Self, Args extends unknown[], Return>(
  funcOrConstOrSelf?: unknown | unknown | Self,
  property?: keyof Self,
): SpyLike<Self, Args, Return>
Parameters
  • funcOrConstOrSelf?unknown | unknown | Self
  • property?keyof Self
function

#stub(3 overloads)

function stub<Self, Prop extends keyof Self>(
  self: Self,
  property: Prop,
): Stub<Self, GetParametersFromProp<Self, Prop>, GetReturnFromProp<Self, Prop>>

Replaces an instance method with a Stub with empty implementation.

Parameters
  • selfSelf

    The instance to replace a method of.

  • propertyProp

    The property of the instance to replace.

Returns

Stub<Self, GetParametersFromProp<Self, Prop>, GetReturnFromProp<Self, Prop>> — The stub function which replaced the original.

Examples

Usage

import { stub, assertSpyCalls } from "@std/testing/mock";

const obj = {
  method() {
    // some inconventient feature for testing
  },
};

const methodStub = stub(obj, "method");

for (const _ of Array(5)) {
  obj.method();
}

assertSpyCalls(methodStub, 5);
Show all 3 overloads
#1
function stub<Self, Prop extends keyof Self>(
  self: Self,
  property: Prop,
): Stub<Self, GetParametersFromProp<Self, Prop>, GetReturnFromProp<Self, Prop>>

Replaces an instance method with a Stub with empty implementation.

Parameters
  • selfSelf

    The instance to replace a method of.

  • propertyProp

    The property of the instance to replace.

Returns

Stub<Self, GetParametersFromProp<Self, Prop>, GetReturnFromProp<Self, Prop>> — The stub function which replaced the original.

#2
function stub<Self, Prop extends keyof Self>(
  self: Self,
  property: Prop,
  func: (this: Self, _: GetParametersFromProp<Self, Prop>) => unknown,
): Stub<Self, GetParametersFromProp<Self, Prop>, GetReturnFromProp<Self, Prop>>

Replaces an instance method with a Stub with the given implementation.

Parameters
  • selfSelf

    The instance to replace a method of.

  • propertyProp

    The property of the instance to replace.

  • func(this: Self, _: GetParametersFromProp<Self, Prop>) => unknown

    The fake implementation of the function.

Returns

Stub<Self, GetParametersFromProp<Self, Prop>, GetReturnFromProp<Self, Prop>> — The stub function which replaced the original.

#3
function stub<Self, Args extends unknown[], Return>(
  self: Self,
  property: keyof Self,
  func?: (this: Self, _: Args) => unknown,
): Stub<Self, Args, Return>
Parameters
  • selfSelf
  • propertykeyof Self
  • func?(this: Self, _: Args) => unknown
function

#toErrorObject

function toErrorObject(err: Error): ErrorObject

Convert an error to an error object

Parameters
  • errError
function

#tryOr

function tryOr<T>(fn: () => unknown, orValue: T): T

Try to execute a function and return the result or a default value if an error occurs.

import { tryOr } from "@core/errorutil/try-or";

console.log(tryOr(() => 1, 2)); // 1
console.log(tryOr(() => { throw "err"; }, 2)); // 2
Parameters
  • fn() => unknown
  • orValueT
function

#tryOrElse

function tryOrElse<T>(fn: () => unknown, elseFn: (err: unknown) => unknown): T

Try to execute a function and return the result or execute another function and return its result if an error occurs.

import { tryOrElse } from "@core/errorutil/try-or-else";

console.log(tryOrElse(() => 1, () => 2)); // 1
console.log(tryOrElse(() => { throw "err" }, () => 2)); // 2
Parameters
  • fn() => unknown
  • elseFn(err: unknown) => unknown
function

#unimplemented

function unimplemented(_: unknown): never

Function indicating that this part is unimplemented.

For example, defining a mock object with unimplemented function should look like this:

import { unimplemented } from "@core/errorutil/unimplemented";

type Service = {
  get(id: string): Promise<string>;
  set(id: string, item: string): Promise<void>;
};

const _mock: Service = {
  get: () => unimplemented(),
  set: () => unimplemented(),
};
Parameters
  • _unknown
function

#unreachable

function unreachable(_: never[]): never

Function indicating that this part is unreachable.

For example, the following code passed type checking.

import { unreachable } from "@core/errorutil/unreachable";

type Animal = "dog" | "cat";

function say(animal: Animal): void {
  switch (animal) {
    case "dog":
      console.log("dog");
      break;
    case "cat":
      console.log("dog");
      break;
    default:
      unreachable(animal);
  }
}
say("dog");

But the following code because a case for "bird" is missing.

import { unreachable } from "@core/errorutil/unreachable";

type Animal = "dog" | "cat" | "bird";

function say(animal: Animal): void {
  switch (animal) {
    case "dog":
      console.log("dog");
      break;
    case "cat":
      console.log("dog");
      break;
    default: {
      // The line below causes a type error if we uncomment it.
      // error: TS2345 [ERROR]: Argument of type 'string' is not assignable to parameter of type 'never'.
      //unreachable(animal);
    }
  }
}
say("dog");
Parameters
  • _never[]

Types

type

#ConnectRpcResponse

type ConnectRpcResponse<T = any> = ConnectRpcResponseSuccess<T>
  | ConnectRpcResponseError<T>
  | ConnectRpcResponseFailure<T>

ConnectRPC response union type.

Use processed to distinguish between server responses and failures:

  • processed === true: Server responded (Success or Error)
  • processed === false: Request failed (Failure)

Use ok to check for success:

  • ok === true: Success (statusCode === 0)
  • ok === false: Error or Failure
type

#DenoKvResult

type DenoKvResult<T = any> = DenoKvGetResult<T>
  | DenoKvSetResult
  | DenoKvDeleteResult
  | DenoKvListResult<T>
  | DenoKvAtomicResult

Union of all Deno KV result types.

type

#ErrorObject

type ErrorObject = {
    proto: string;
    name: string;
    message: string;
    stack?: string;
    attributes: Record<string, unknown>;
  }

An error object is a serializable representation of an error

NameDescription
protoThe name of the error prototype
nameThe name of the error
messageThe error message
stackThe error stack
attributesAdditional attributes
Properties
  • protostring

    The name of the error prototype

  • namestring

    The name of the error

  • messagestring

    The error message

  • stack?string

    The error stack

  • attributesRecord<string, unknown>

    Additional attributes

type

#Failure

type Failure<E> = [E, undefined]
type

#GraphqlResponse

type GraphqlResponse<T = any> = GraphqlResponseSuccess<T> | GraphqlResponseError<T> | GraphqlResponseFailure<T>

GraphQL response union type.

Use processed to distinguish between server responses and failures:

  • processed === true: Server responded (Success or Error)
  • processed === false: Request failed (Failure)

Use ok to check for success:

  • ok === true: Success (no errors)
  • ok === false: Error or Failure
type

#HttpResponse

type HttpResponse<T = any> = HttpResponseSuccess<T> | HttpResponseError<T> | HttpResponseFailure<T>

HTTP response union type representing all possible response states.

  • Success (2xx): processed: true, ok: true, error: null
  • Error (4xx/5xx): processed: true, ok: false, error: HttpError
  • Failure (network error): processed: false, ok: false, error: Error
type

#MongoResult

type MongoResult<T = any> = MongoFindResult<T>
  | MongoInsertOneResult
  | MongoInsertManyResult
  | MongoUpdateResult
  | MongoDeleteResult
  | MongoFindOneResult<T>
  | MongoCountResult

Union of all MongoDB result types.

type

#RabbitMqResult

type RabbitMqResult = RabbitMqPublishResult
  | RabbitMqConsumeResult
  | RabbitMqAckResult
  | RabbitMqQueueResult
  | RabbitMqExchangeResult

Union of all RabbitMQ result types.

type

#RedisResult

type RedisResult<T = any> = RedisCommonResult<T>
  | RedisGetResult
  | RedisSetResult
  | RedisCountResult
  | RedisArrayResult<T>
  | RedisHashResult

Union of all Redis result types.

type

#Result

type Result<T, E> = Success<T> | Failure<E>
type

#SpyLike

type SpyLike<Self = any, Args extends unknown[] = any[], Return = any> = Spy<Self, Args, Return> | ConstructorSpy<Self, Args>

SpyLink object type.

type

#SqlQueryResult

type SqlQueryResult<T = any> = SqlQueryResultSuccess<T> | SqlQueryResultError<T> | SqlQueryResultFailure<T>

SQL query result union type representing all possible result states.

  • Success: processed: true, ok: true, error: null
  • Error: processed: true, ok: false, error: SqlError
  • Failure: processed: false, ok: false, error: SqlConnectionError
type

#SqsResult

type SqsResult = SqsSendResult
  | SqsSendBatchResult
  | SqsReceiveResult
  | SqsDeleteResult
  | SqsDeleteBatchResult
  | SqsEnsureQueueResult
  | SqsDeleteQueueResult

Union type of all SQS result types.

type

#StepContext

type StepContext<P = unknown, A extends readonly unknown[] = readonly unknown[], R extends Record<string, unknown> = Record<string, unknown>> = StepContext & { previous: P; results: A; resources: R }

Execution context provided to steps, resources, and setup hooks.

The context provides access to:

  • Previous step results with full type inference
  • All accumulated results as a typed tuple
  • Named resources registered with .resource()
  • Shared storage for cross-step communication
  • Abort signal for timeout and cancellation handling
type

#Success

type Success<T> = [undefined, T]

Variables

const

#isErrorObject

const isErrorObject: (x: unknown) => unknown

Check if a value is an error object

const

#outdent

const outdent: Outdent
Search Documentation