@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
Links
Related Packages
| Package | Description |
|---|---|
| @probitas/builder | Fluent API for building scenario definitions |
| @probitas/runner | Test execution engine with retry and concurrency |
| @probitas/reporter | Output formatters (list, dot, TAP, JSON) |
| @probitas/scenario | Core type definitions and utilities |
| @probitas/discover | Scenario file discovery |
| @probitas/logger | Unified logging interface |
| @probitas/cli | Command-line interface |
Core Exports
scenario- Factory function to create scenario buildersSkip- Utility to skip steps or scenarios conditionallyStepContext- Type representing the context passed to each stepclient- Namespace containing all available client implementationsexpect- Assertion utilities (from@std/expect)
Re-exported Utilities
For convenience, this module also re-exports commonly used testing utilities:
faker- Fake data generation from@jackfiszr/fakerFakeTime- Time mocking utilities from@std/testing/timespy,stub,assertSpyCalls- Mock utilities from@std/testing/mocktryOr,raise- Error handling utilities from@core/errorutiloutdent- Template literal tag for removing indentation
Installation
deno add jsr:@probitas/probitasClasses
#Faker
class FakerMain Faker class
Constructor
new Faker(opts: Record<string, unknown>)Constructor for the Faker class
Properties
optsRecord<string, unknown>localesRecord<string, Locale>localestringlocaleFallbackstringfakeunknownuniqueunknownrandomRandomhelpersHelpersnameNameaddressAddresscompanyCompanyfinanceFinanceimageImageloremLoremhackerHackerinternetInternetdatabaseDatabasephonePhonedate_DatecommerceCommercesystemSystemgitGitvehicleVehicledefinitionsDefinitionsseedValue?number | number[]
Methods
setLocale(): unknownseed(): unknown#FakeTime
class FakeTimeOverrides 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);
});
| Name | Description |
|---|---|
[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](): unknownRestores real time.
static restore(): unknownRestores real time.
static restoreFor(): unknownRestores real time temporarily until callback returns and resolves.
now(): unknownThe number of milliseconds elapsed since the epoch (January 1, 1970 00:00:00 UTC) for the fake time.
now(): unknownSet 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(): unknownThe initial number of milliseconds elapsed since the epoch (January 1, 1970 00:00:00 UTC) for the fake time.
delay(): unknownResolves after the given number of milliseconds using real time.
runMicrotasks(): unknownRuns all pending microtasks.
tick(): unknownAdds 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(): unknownRuns 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(): unknownAdvances time to when the next scheduled timer is due. If there are no pending timers, time will not be changed.
nextAsync(): unknownRuns 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(): unknownAdvances 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(): unknownAdvances 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(): unknownRestores time related global functions to their original state.
#MockError
class MockError extends ErrorErrorAn 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
#Skip
class Skip extends ErrorErrorException class for conditionally skipping scenario execution.
Throw Skip from any step, setup, or resource fn to skip the
entire scenario. Skipped scenarios are counted separately in the
summary and don't count as failures.
Common use cases:
- Feature flags or environment checks
- Prerequisites not met
- Platform-specific tests
- Temporary test disabling with clear reason
Examples
Skip based on environment
import { scenario, Skip } from "@probitas/probitas";
scenario("Production Only")
.step("Check environment", () => {
if (Deno.env.get("ENV") !== "production") {
throw new Skip("Only runs in production");
}
})
.step("Production test", () => { ... })
.build();
Skip based on resource availability
scenario("Database Test")
.resource("db", async () => {
try {
return await Database.connect();
} catch {
throw new Skip("Database not available");
}
})
.step("Query data", (ctx) => ctx.resources.db.query(...))
.build();
Skip with feature flag
scenario("Beta Feature")
.step("Check feature flag", (ctx) => {
if (!ctx.store.get("betaEnabled")) {
throw new Skip("Beta feature not enabled");
}
})
.build();
| Name | Description |
|---|---|
reason | Human-readable reason for skipping. |
Constructor
new Skip(reason?: string)Create a Skip exception.
Properties
- readonly
reason?stringHuman-readable reason for skipping.
When provided, this reason is displayed in test reports. If not provided, defaults to
undefined(the error message will still show "Skipped").
#SqlQueryResult
class SqlQueryResult<T = Record<string, any>>SQL query result with rows, metadata, and transformation methods.
| Name | Description |
|---|---|
ok | — |
rows | — |
rowCount | — |
duration | — |
metadata | — |
map() | Map rows to a new type. |
as() | Create class instances from rows. |
Constructor
new SqlQueryResult(init: SqlQueryResultInit<T>)Properties
- readonly
okboolean - readonly
rowCountnumber - readonly
durationnumber
Methods
map(): unknownMap rows to a new type.
as(): unknownCreate class instances from rows.
#TimeError
class TimeError extends ErrorErrorRepresents 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.
#UnimplementedError
class UnimplementedError extends ErrorErrorError indicating that this part is unimplemented.
Constructor
new UnimplementedError(_: unknown)Interfaces
#ConnectRpcResponse
interface ConnectRpcResponseConnectRPC response interface.
| Name | Description |
|---|---|
type | Result type identifier |
ok | Whether the request was successful (code === 0). |
code | ConnectRPC/gRPC status code. |
message | Status message (empty string for successful responses). |
headers | Response headers |
trailers | Response trailers (sent at end of RPC) |
duration | Response time in milliseconds. |
data() | Get deserialized response data. |
raw() | Get raw response message. |
Properties
- readonly
type"connectrpc"Result type identifier
- readonly
okbooleanWhether the request was successful (code === 0).
ConnectRPC/gRPC status code.
- readonly
messagestringStatus message (empty string for successful responses).
- readonly
headersRecord<string, string>Response headers
- readonly
trailersRecord<string, string>Response trailers (sent at end of RPC)
- readonly
durationnumberResponse time in milliseconds.
Methods
data<T = any>(): T | nullGet deserialized response data. Returns the response message as-is (already deserialized by Connect). Returns null if the response is an error or has no data.
raw(): unknownGet raw response message.
#ConstructorSpy
interface ConstructorSpy<Self = any, Args extends unknown[] = any[]>A constructor wrapper that records all calls made to it.
| Name | Description |
|---|---|
original | The function that is being spied on. |
calls | Information about calls made to the function or instance method. |
restored | Whether 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) => unknownThe function that is being spied on.
callsSpyCall<Self, Args, Self>[]Information about calls made to the function or instance method.
restoredbooleanWhether or not the original instance method has been restored.
Methods
restore(): voidIf spying on an instance method, this restores the original instance method.
#DelayOptions
interface DelayOptionsOptions for delay.
| Name | Description |
|---|---|
signal | Signal used to abort the delay. |
persistent | Indicates whether the process should continue to run as long as the timer exists. |
Properties
signal?AbortSignalSignal used to abort the delay.
persistent?booleanIndicates whether the process should continue to run as long as the timer exists.
#ExpectedSpyCall
interface ExpectedSpyCall<Self = any, Args extends unknown[] = any[], Return = any>Call information recorded by a spy.
| Name | Description |
|---|---|
args | Arguments passed to a function when called. |
self | The instance that a method was called on. |
returned | The value that was returned by a function. |
error | The expected thrown error. |
Properties
args?[unknown, unknown]Arguments passed to a function when called.
self?SelfThe instance that a method was called on.
returned?ReturnThe 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.
#FakeTimeOptions
interface FakeTimeOptionsThe option for FakeTime
| Name | Description |
|---|---|
advanceRate | The rate relative to real time at which fake time is updated. |
advanceFrequency | The frequency in milliseconds at which fake time is updated. |
Properties
advanceRatenumberThe 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?numberThe frequency in milliseconds at which fake time is updated. If advanceRate is set, we will update the time every 10 milliseconds by default.
#GraphqlResponse
interface GraphqlResponse<T = any>GraphQL response interface with pre-loaded body.
| Name | Description |
|---|---|
type | Result type identifier |
ok | Whether the request was successful (no errors) |
errors | GraphQL errors array (null if no errors) |
extensions | Response extensions |
duration | Response time in milliseconds |
status | HTTP status code |
headers | Headers from the HTTP response |
raw | Raw Web standard Response (for streaming or special cases) |
data() | Get response data (null if no data). |
Properties
- readonly
type"graphql"Result type identifier
- readonly
okbooleanWhether the request was successful (no errors)
GraphQL errors array (null if no errors)
- readonly
extensions?Record<string, unknown>Response extensions
- readonly
durationnumberResponse time in milliseconds
- readonly
statusnumberHTTP status code
- readonly
headersHeadersHeaders from the HTTP response
- readonly
rawglobalThis.ResponseRaw Web standard Response (for streaming or special cases)
Methods
data<U = T>(): U | nullGet response data (null if no data). Does not throw even if errors are present.
#HttpResponse
interface HttpResponseHTTP response with pre-loaded body for synchronous access.
Wraps Web standard Response, allowing body to be read synchronously and multiple times (unlike the streaming-based standard Response).
| Name | Description |
|---|---|
type | Result type identifier |
ok | Whether the response was successful (status 200-299) |
status | HTTP status code |
statusText | HTTP status text |
headers | Response headers |
url | Request URL |
body | Response body as raw bytes (null if no body) |
duration | Response time in milliseconds |
raw | Raw Web standard Response (for streaming or special cases) |
arrayBuffer() | Get body as ArrayBuffer (null if no body) |
blob() | Get body as Blob (null if no body) |
text() | Get body as text (null if no body) |
json() | Get body as parsed JSON (null if no body) |
Properties
- readonly
type"http"Result type identifier
- readonly
okbooleanWhether the response was successful (status 200-299)
- readonly
statusnumberHTTP status code
- readonly
statusTextstringHTTP status text
- readonly
headersHeadersResponse headers
- readonly
urlstringRequest URL
- readonly
bodyUint8Array | nullResponse body as raw bytes (null if no body)
- readonly
durationnumberResponse time in milliseconds
- readonly
rawglobalThis.ResponseRaw Web standard Response (for streaming or special cases)
Methods
arrayBuffer(): ArrayBuffer | nullGet body as ArrayBuffer (null if no body)
blob(): Blob | nullGet body as Blob (null if no body)
text(): string | nullGet body as text (null if no body)
json<T = any>(): T | nullGet body as parsed JSON (null if no body)
#MethodSpy
interface MethodSpy<Self = any, Args extends unknown[] = any[], Return = any> extends Spy<Self, Args, Return>, DisposableAn instance method wrapper that records all calls made to it.
#Options
interface Options| Name | Description |
|---|---|
trimLeadingNewline | — |
trimTrailingNewline | — |
newline | Normalize all newlines in the template literal to this value. |
Properties
trimLeadingNewline?booleantrimTrailingNewline?booleannewline?string | nullNormalize 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 ' '.
#Outdent
interface Outdent| Name | Description |
|---|---|
string() | Remove indentation from a string |
Methods
string(str: string): stringRemove indentation from a string
Parameters
strstring
#Spy
interface Spy<Self = any, Args extends unknown[] = any[], Return = any>A function or instance method wrapper that records all calls made to it.
| Name | Description |
|---|---|
original | The function that is being spied on. |
calls | Information about calls made to the function or instance method. |
restored | Whether 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) => unknownThe function that is being spied on.
callsSpyCall<Self, Args, Return>[]Information about calls made to the function or instance method.
restoredbooleanWhether or not the original instance method has been restored.
Methods
restore(): voidIf spying on an instance method, this restores the original instance method.
#SpyCall
interface SpyCall<Self = any, Args extends unknown[] = any[], Return = any>Call information recorded by a spy.
| Name | Description |
|---|---|
args | Arguments passed to a function when called. |
returned | The value that was returned by a function. |
error | The error value that was thrown by a function. |
self | The instance that a method was called on. |
Properties
argsArgsArguments passed to a function when called.
returned?ReturnThe value that was returned by a function.
error?ErrorThe error value that was thrown by a function.
self?SelfThe instance that a method was called on.
#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.
| Name | Description |
|---|---|
fake | The function that is used instead of the original. |
Properties
fake(this: Self, _: Args) => unknownThe function that is used instead of the original.
Functions
#alter
function alter<T, E>(fn: () => unknown, alt: E): TAlter 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
#alterElse
function alterElse<T, E>(fn: () => unknown, elseFn: (err: unknown) => unknown): TAlter 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
#assertSpyCall
function assertSpyCall<Self, Args extends unknown[], Return>(spy: SpyLike<Self, Args, Return>, callIndex: number, expected?: ExpectedSpyCall<Self, Args, Return>): voidAsserts that a spy is called as expected.
Parameters
spySpyLike<Self, Args, Return>The spy to check
callIndexnumberThe 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 });
#assertSpyCallArg
function assertSpyCallArg<Self, Args extends unknown[], Return, ExpectedArg>(spy: SpyLike<Self, Args, Return>, callIndex: number, argIndex: number, expected: ExpectedArg): ExpectedArgAsserts that a spy is called with a specific arg as expected.
Parameters
spySpyLike<Self, Args, Return>The spy to check.
callIndexnumberThe index of the call to check.
argIndexnumberThe index of the arguments to check.
expectedExpectedArgThe 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);
#assertSpyCallArgs(4 overloads)
function assertSpyCallArgs<Self, Args extends unknown[], Return, ExpectedArgs extends unknown[]>(spy: SpyLike<Self, Args, Return>, callIndex: number, expected: ExpectedArgs): ExpectedArgsAsserts 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.
callIndexnumberThe index of the call to check.
expectedExpectedArgsThe 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
function assertSpyCallArgs<Self, Args extends unknown[], Return, ExpectedArgs extends unknown[]>(spy: SpyLike<Self, Args, Return>, callIndex: number, expected: ExpectedArgs): ExpectedArgsAsserts 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.
callIndexnumberThe index of the call to check.
expectedExpectedArgsThe expected arguments.
Returns
ExpectedArgs — The actual arguments.
function assertSpyCallArgs<Self, Args extends unknown[], Return, ExpectedArgs extends unknown[]>(spy: SpyLike<Self, Args, Return>, callIndex: number, argsStart: number, expected: ExpectedArgs): ExpectedArgsAsserts 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.
callIndexnumberThe index of the call to check.
argsStartnumberThe start index of the arguments to check. If not specified, it checks the arguments from the beignning.
expectedExpectedArgsThe expected arguments.
Returns
ExpectedArgs — The actual arguments.
function assertSpyCallArgs<Self, Args extends unknown[], Return, ExpectedArgs extends unknown[]>(spy: SpyLike<Self, Args, Return>, callIndex: number, argsStart: number, argsEnd: number, expected: ExpectedArgs): ExpectedArgsAsserts 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
callIndexnumberThe index of the call to check
argsStartnumberThe start index of the arguments to check. If not specified, it checks the arguments from the beignning.
argsEndnumberThe end index of the arguments to check. If not specified, it checks the arguments until the end.
expectedExpectedArgsThe expected arguments.
Returns
ExpectedArgs — The actual arguments
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): ExpectedArgsParameters
spySpyLike<Self, Args, Return>callIndexnumberargsStart?number | ExpectedArgsargsEnd?number | ExpectedArgsexpected?ExpectedArgs
#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
callIndexnumberThe 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 });
#assertSpyCalls
function assertSpyCalls<Self, Args extends unknown[], Return>(spy: SpyLike<Self, Args, Return>, expectedCalls: number): voidAsserts that a spy is called as much as expected and no more.
Parameters
spySpyLike<Self, Args, Return>The spy to check
expectedCallsnumberThe number of the expected calls.
Examples
Usage
import { assertSpyCalls, spy } from "@std/testing/mock";
const func = spy();
func();
func();
assertSpyCalls(func, 2);
#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]
#expect(11 overloads)
function expect<T extends HttpResponse>(value: T): ReturnType<expectHttpResponse>Unified expect function that dispatches to the appropriate expectation function based on the type of the input object.
Parameters
valueT
Examples
// HTTP response
const httpRes = await http.get("/users");
expect(httpRes).toBeSuccessful().toHaveContentContaining({ users: [] });
// GraphQL response
const gqlRes = await graphql.query("{ users { id name } }");
expect(gqlRes).toBeSuccessful().toHaveContent();
// SQL query result
const sqlRes = await db.query("SELECT * FROM users");
expect(sqlRes).toBeSuccessful().toHaveCount(10);
// MongoDB result
const mongoRes = await mongo.find({ status: "active" });
expect(mongoRes).toBeSuccessful().toHaveLength(10);
// Falls back to expectAnything (chainable @std/expect) for other values
expect(42).toBe(42).toBeGreaterThan(40);
Show all 11 overloads
function expect<T extends HttpResponse>(value: T): ReturnType<expectHttpResponse>Unified expect function that dispatches to the appropriate expectation function based on the type of the input object.
Parameters
valueT
function expect<T extends ConnectRpcResponse>(value: T): ReturnType<expectConnectRpcResponse>Parameters
valueT
function expect<T extends GraphqlResponse>(value: T): ReturnType<expectGraphqlResponse>Parameters
valueT
function expect<T extends SqlQueryResult>(value: T): SqlQueryResultExpectation<ExtractSqlRowType<T>>Parameters
valueT
function expect<T extends DenoKvResult>(value: T): ReturnType<expectDenoKvResult>Parameters
valueT
function expect<T extends RedisResult>(value: T): ReturnType<expectRedisResult>Parameters
valueT
function expect<T extends MongoResult>(value: T): ReturnType<expectMongoResult>Parameters
valueT
function expect<T extends RabbitMqResult>(value: T): ReturnType<expectRabbitMqResult>Parameters
valueT
function expect<T extends SqsResult>(value: T): ReturnType<expectSqsResult>Parameters
valueT
function expect(value: unknown): AnythingExpectationParameters
valueunknown
function expect(value: unknown): unknownParameters
valueunknown
#fromErrorObject
function fromErrorObject(obj: ErrorObject): ErrorConvert an error object to an error
Parameters
objErrorObject
#mockSession(3 overloads)
function mockSession(): numberCreates 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
function mockSession(): numberCreates 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.
function mockSession<Self, Args extends unknown[], Return>(func: (this: Self, _: Args) => unknown): (this: Self, _: Args) => unknownCreates 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) => unknownThe function to be used for the created session.
Returns
(this: Self, _: Args) => unknown — The function to execute the session.
function mockSession<Self, Args extends unknown[], Return>(func?: (this: Self, _: Args) => unknown): number | unknownParameters
func?(this: Self, _: Args) => unknown
#mockSessionAsync
function mockSessionAsync<Self, Args extends unknown[], Return>(func: (this: Self, _: Args) => unknown): (this: Self, _: Args) => unknownCreates an async session that tracks all mocks created before the promise resolves.
Parameters
func(this: Self, _: Args) => unknownThe 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
#raise
function raise(err: unknown): neverThrow 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
#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) => unknownCreates 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);
#restore
function restore(id?: number): voidRestores 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?numberThe 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);
#returnsArg
function returnsArg<Arg, Self = any>(idx: number): (this: Self, _: Arg[]) => unknownCreates a function that returns one of its arguments.
Parameters
idxnumberThe 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);
#returnsArgs
function returnsArgs<Args extends unknown[], Self = any>(_: unknown, end?: number): (this: Self, _: Args) => unknownCreates 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
_unknownend?numberThe 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]);
#returnsNext
function returnsNext<Return, Self = any, Args extends unknown[] = any[]>(values: Iterable<Return | Error>): (this: Self, _: Args) => unknownCreates 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);
#returnsThis
function returnsThis<Self = any, Args extends unknown[] = any[]>(): (this: Self, _: Args) => unknownCreates 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);
#scenario
function scenario(name: string, options?: ScenarioOptions): ScenarioBuilderInitCreate 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)
options?ScenarioOptions- 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";
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
scenario("Payment Integration", {
tags: ["integration", "payment", "slow"],
stepOptions: { timeout: 60000 } // 1 minute timeout for all steps
})
.step("Process payment", async () => { ... })
.build();
// Run with: probitas run -s "tag:payment"
Scenario with resources and setup
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(...))
.step("Query data", (ctx) => ctx.resources.db.query(...))
.build();
#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
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.
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) => unknownThe function to wrap
Returns
Spy<Self, Args, Return> — The wrapped function.
function spy<Self, Args extends unknown[]>(constructor: (_: Args) => unknown): ConstructorSpy<Self, Args>Create a spy constructor.
Parameters
constructor(_: Args) => unknownThe constructor to spy.
Returns
ConstructorSpy<Self, Args> — The wrapped constructor.
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
selfSelfThe instance to spy.
propertyPropThe property of the method to spy.
Returns
MethodSpy<Self, GetParametersFromProp<Self, Prop>, GetReturnFromProp<Self, Prop>> — The spy function.
function spy<Self, Args extends unknown[], Return>(funcOrConstOrSelf?: unknown | unknown | Self, property?: keyof Self): SpyLike<Self, Args, Return>Parameters
funcOrConstOrSelf?unknown | unknown | Selfproperty?keyof Self
#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
selfSelfThe instance to replace a method of.
propertyPropThe 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
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
selfSelfThe instance to replace a method of.
propertyPropThe property of the instance to replace.
Returns
Stub<Self, GetParametersFromProp<Self, Prop>, GetReturnFromProp<Self, Prop>> — The stub function which replaced the original.
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
selfSelfThe instance to replace a method of.
propertyPropThe property of the instance to replace.
func(this: Self, _: GetParametersFromProp<Self, Prop>) => unknownThe fake implementation of the function.
Returns
Stub<Self, GetParametersFromProp<Self, Prop>, GetReturnFromProp<Self, Prop>> — The stub function which replaced the original.
function stub<Self, Args extends unknown[], Return>(self: Self, property: keyof Self, func?: (this: Self, _: Args) => unknown): Stub<Self, Args, Return>Parameters
selfSelfpropertykeyof Selffunc?(this: Self, _: Args) => unknown
#toErrorObject
function toErrorObject(err: Error): ErrorObjectConvert an error to an error object
Parameters
errError
#tryOr
function tryOr<T>(fn: () => unknown, orValue: T): TTry 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() => unknownorValueT
#tryOrElse
function tryOrElse<T>(fn: () => unknown, elseFn: (err: unknown) => unknown): TTry 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() => unknownelseFn(err: unknown) => unknown
#unimplemented
function unimplemented(_: unknown): neverFunction 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
#unreachable
function unreachable(_: never[]): neverFunction 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[]
Type Aliases
#Definitions
type Definitions = { name: DefinitionCategory & NameModule; address: DefinitionCategory & AddressModule; company: DefinitionCategory; lorem: DefinitionCategory; hacker: DefinitionCategory; phone_number: DefinitionCategory; finance: DefinitionCategory & FinanceDefinitions; internet: DefinitionCategory; commerce: DefinitionCategory & CommerceModule; database: DefinitionCategory; system: DefinitionCategory; date: DefinitionCategory & DateDefinition; vehicle: DefinitionCategory; title: string; separator: string }| Name | Description |
|---|---|
name | — |
address | — |
company | — |
lorem | — |
hacker | — |
phone_number | — |
finance | — |
internet | — |
commerce | — |
database | — |
system | — |
date | — |
vehicle | — |
title | — |
separator | — |
Properties
nameDefinitionCategory & NameModuleaddressDefinitionCategory & AddressModulecompanyDefinitionCategoryloremDefinitionCategoryhackerDefinitionCategoryphone_numberDefinitionCategoryfinanceDefinitionCategory & FinanceDefinitionsinternetDefinitionCategorycommerceDefinitionCategory & CommerceModuledatabaseDefinitionCategorysystemDefinitionCategorydateDefinitionCategory & DateDefinitionvehicleDefinitionCategorytitlestringseparatorstring
#DenoKvResult
type DenoKvResult<T = unknown> = DenoKvGetResult<T> | DenoKvSetResult | DenoKvDeleteResult | DenoKvListResult<T> | DenoKvAtomicResultUnion of all Deno KV result types. Used by expectDenoKvResult to determine the appropriate expectation 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
| Name | Description |
|---|---|
proto | The name of the error prototype |
name | The name of the error |
message | The error message |
stack | The error stack |
attributes | Additional attributes |
Properties
protostringThe name of the error prototype
namestringThe name of the error
messagestringThe error message
stack?stringThe error stack
attributesRecord<string, unknown>Additional attributes
#Failure
type Failure<E> = [E, undefined]#Locale
type Locale = Record<string, string | NameModule | AddressModule | Record<string, unknown>>#MongoResult
type MongoResult<T = any> = MongoFindResult<T> | MongoInsertOneResult | MongoInsertManyResult | MongoUpdateResult | MongoDeleteResult | MongoFindOneResult<T> | MongoCountResultUnion of all MongoDB result types. Used by expectMongoResult to determine the appropriate expectation type.
#RabbitMqResult
type RabbitMqResult = RabbitMqPublishResult | RabbitMqConsumeResult | RabbitMqAckResult | RabbitMqQueueResult | RabbitMqExchangeResultUnion of all RabbitMQ result types. Used by expectRabbitMqResult to determine the appropriate expectation type.
#RedisResult
type RedisResult<T = unknown> = RedisCommonResult<T> | RedisGetResult | RedisSetResult | RedisCountResult | RedisArrayResult<T> | RedisHashResultUnion of all Redis result types. Used by expectRedisResult to determine the appropriate expectation type.
#Result
type Result<T, E> = Success<T> | Failure<E>#SpyLike
type SpyLike<Self = any, Args extends unknown[] = any[], Return = any> = Spy<Self, Args, Return> | ConstructorSpy<Self, Args>SpyLink object type.
#SqsResult
type SqsResult = SqsSendResult | SqsSendBatchResult | SqsReceiveResult | SqsDeleteResult | SqsDeleteBatchResult | SqsEnsureQueueResult | SqsDeleteQueueResultUnion type of all SQS result types. Used for type-safe handling in the unified expectSqsResult function.
#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
#Success
type Success<T> = [undefined, T]Variables
#outdent
const outdent: Outdent