Skip to content
Logic SDK
Esc
↑↓navigate↵open⌘Jpreview
On this page

Quickstart

Set up a module, run one query, and test its result.

Run and test a query without a database.

1. Create a project

In a terminal, run these commands.

mkdir booking-demo
cd booking-demo
bun init -y
bun add logic-sdk zod

Your package.json lists logic-sdk and zod.

2. Define a module

Create logic.ts. It declares the scope type once for the whole app.

import { 
function init<C extends Config & OnlyKnownKeys<C>>(): {
    createRegistry: <const Mods extends Record<string, object>, T = ScopeOf<C>>(options: TypedOptions<C, Mods, T>) => Registry<ScopeOf<C>, Mods, ConfigOf<C>, ServicesOf<C>, AppError<`${string extends keyof Mods ? keyof Mods & string : { [M in keyof Mods & string]: { [N in keyof Mods[M] & string]: Mods[M][N] extends Fn<Kind, any, any, any, any, any, infer Id extends string | undefined> ? `${M}.${Id extends string ? Id : N}` : never; }[keyof Mods[M] & string]; }[keyof Mods & string] | (keyof Mods & string)}.forbidden`, undefined> | AppError<`${string extends keyof Mods ? keyof Mods & string : { [M in keyof Mods & string]: { [N in keyof Mods[M] & string]: Mods[M][N] extends Fn<Kind, any, any, any, any, any, infer Id extends string | undefined> ? `${M}.${Id extends string ? Id : N}` : never; }[keyof Mods[M] & string]; }[keyof Mods & string]}.invalidInput`, {
        issues: {
            message: string;
            path?: PropertyKey[];
        }[];
    }> | AppError<`${string extends keyof Mods ? keyof Mods & string : keyof Mods & string}.notFound`, undefined> | { [M in keyof Mods & string]: { [N in keyof Mods[M] & string]: Mods[M][N] extends ErrorDef<any, infer O, infer Id extends string | undefined> ? AppError<`${M}.${Id extends string ? Id : N}`, O> : never; }[keyof Mods[M] & string]; }[keyof Mods & string]>;
    query: Constructor<C, "query">;
    mutation: Constructor<C, "mutation">;
    action: Constructor<C, "action">;
    event: <S extends Schema, const Id extends string | undefined = undefined>(def: {
        id?: Id;
        payload: S;
    }) => EventDef<In<S>, Out<S>, Id, S>;
    error: <S extends Schema | undefined = undefined, const Id extends string | undefined = undefined>(def?: {
        id?: Id;
        kind?: Exclude<ErrorKind, "invalid">;
        details?: S;
        message?: string | ((details: S extends Schema ? Out<S> : undefined) => string);
        meta?: Readonly<Record<string, unknown>>;
    }) => ErrorDef<S extends Schema ? In<S> : undefined, S extends Schema ? Out<S> : undefined, Id>;
    cron: <const Sc extends ScopeOf<C>>(def: CronDef<...>) => Cron<C>;
    listener: <O>(def: {
        id?: string;
        event: () => EventDef<unknown, O>;
        attempts?: number;
        delay?: number;
        when?: (payload: O) => boolean;
        key?: (payload: O) => string;
        unique?: (payload: O) => string;
        scope?: (payload: O) => ScopeOf<C>;
        timeout?: number;
        queue?: string;
        meta?: MetaOf<C>;
        handler: (ctx: ListenerCtx<C, O>, payload: O) => Promise<unknown>;
        retry?: (error: AppError) => boolean;
        failed?: (ctx: ListenerCtx<C, O>, payload: O, error: unknown) => Promise<unknown>;
    }) => Listener<O, C>;
}
Typed constructors for your app: ```ts export const { query, mutation, action, event, listener, createRegistry } = init<Config>(); ```
init
} from "logic-sdk";
export const {
const query: Constructor<{
    scope: {
        currency: string;
    };
}, "query">
Reads data. Can run other queries. No writes, no events, no services.
query
,
const createRegistry: <const Mods extends Record<string, object>, T = {
    currency: string;
}>(options: TypedOptions<{
    scope: {
        currency: string;
    };
}, Mods, T>) => Registry<{
    currency: string;
}, Mods, Record<string, never>, {}, AppError<`${string extends keyof Mods ? keyof Mods & string : (keyof Mods & string) | { [M in keyof Mods & string]: { [N in keyof Mods[M] & string]: Mods[M][N] extends Fn<Kind, any, any, any, any, any, infer Id extends string | undefined> ? `${M}.${Id extends string ? Id : N}` : never; }[keyof Mods[M] & string]; }[keyof Mods & string]}.forbidden`, undefined> | AppError<...> | AppError<...> | { [M in keyof Mods & string]: { [N in keyof Mods[M] & string]: Mods[M][N] extends ErrorDef<...> ? AppError<...> : never; }[keyof Mods[M] & string]; }[keyof Mods & string]>
Create the registry once at startup: `createRegistry({ modules, database, services })`.
createRegistry
} =
init<{
    scope: {
        currency: string;
    };
}>(): {
    createRegistry: <Mods, T>(options: TypedOptions<{
        scope: {
            currency: string;
        };
    }, Mods, T>) => Registry<{
        currency: string;
    }, Mods, Record<string, never>, {}, AppError<`${string extends keyof Mods ? keyof Mods & string : (keyof Mods & string) | { [M in keyof Mods & string]: { [N in keyof Mods[M] & string]: Mods[M][N] extends Fn<Kind, any, any, any, any, any, infer Id extends string | undefined> ? `${M}.${Id extends string ? Id : N}` : never; }[keyof Mods[M] & string]; }[keyof Mods & string]}.forbidden`, undefined> | AppError<...> | AppError<...> | { [M in keyof Mods & string]: { [N in keyof Mods[M] & string]: Mods[M][N] extends ErrorDef<...> ? AppError<...> : never; }[keyof Mods[M] & string]; }[keyof Mods & string]>;
    ... 6 more ...;
    listener: <O>(def: {
        ...;
    }) => Listener<...>;
}
Typed constructors for your app: ```ts export const { query, mutation, action, event, listener, createRegistry } = init<Config>(); ```
init
<{
scope: {
    currency: string;
}
scope
: { currency: stringcurrency: string } }>();

Create pricing.ts.

import { import zz } from "zod";
import { 
const query: Constructor<{
    scope: {
        currency: string;
    };
}, "query">
Reads data. Can run other queries. No writes, no events, no services.
query
} from "./logic";
/** Price a stay at a fixed nightly rate. */ export const
const priceStay: Fn<"query", {
    nights: number;
}, {
    total: number;
    currency: string;
}, false, {
    scope: {
        currency: string;
    };
}, z.ZodObject<{
    nights: z.ZodNumber;
}, z.core.$strip>, undefined>
Price a stay at a fixed nightly rate.
priceStay
=
query<z.ZodObject<{
    nights: z.ZodNumber;
}, z.core.$strip>, undefined, {
    total: number;
    currency: string;
}, Policy<{
    currency: string;
}>, never, undefined>(def: Def<{
    scope: {
        currency: string;
    };
}, "query", z.ZodObject<{
    nights: z.ZodNumber;
}, z.core.$strip>, undefined, {
    total: number;
    currency: string;
}, Policy<{
    currency: string;
}>, never, undefined>): Fn<"query", {
    nights: number;
}, {
    total: number;
    currency: string;
}, false, {
    scope: {
        currency: string;
    };
}, z.ZodObject<{
    nights: z.ZodNumber;
}, z.core.$strip>, undefined>
query
({
input?: z.ZodObject<{
    nights: z.ZodNumber;
}, z.core.$strip> | undefined
What callers pass, validated on every call. Leave it out when the function takes nothing.
input
: import zz.
function object<{
    nights: z.ZodNumber;
}>(shape?: {
    nights: z.ZodNumber;
} | undefined, params?: string | {
    error?: string | z.core.$ZodErrorMap<NonNullable<z.core.$ZodIssueInvalidType<unknown> | z.core.$ZodIssueUnrecognizedKeys>> | undefined;
    message?: string | undefined | undefined;
} | undefined): z.ZodObject<{
    nights: z.ZodNumber;
}, z.core.$strip>
object
({ nights: z.ZodNumbernights: import zz.function number(params?: string | z.core.$ZodNumberParams): z.ZodNumbernumber()._ZodNumber<$ZodNumberInternals<number>>.int(params?: string | z.core.$ZodCheckNumberFormatParams): z.ZodNumber
Consider `z.int()` instead. This API is considered *legacy*; it will never be removed but a better alternative exists.
int
()._ZodNumber<$ZodNumberInternals<number>>.positive(params?: string | z.core.$ZodCheckGreaterThanParams): z.ZodNumberpositive() }),
async
handler: (ctx: QueryCtx<{
    scope: {
        currency: string;
    };
}, {
    currency: string;
}>, input: {
    nights: number;
}) => Promise<{
    total: number;
    currency: string;
}>
handler
(
ctx: QueryCtx<{
    scope: {
        currency: string;
    };
}, {
    currency: string;
}>
ctx
, { nights: numbernights }) {
return { total: numbertotal: nights: numbernights * 100, currency: stringcurrency:
ctx: QueryCtx<{
    scope: {
        currency: string;
    };
}, {
    currency: string;
}>
ctx
.
BaseCtx<{ scope: { currency: string; }; }, { currency: string; }>.scope: {
    currency: string;
}
scope
.currency: stringcurrency };
}, });

Your module exports priceStay. Its input requires a positive whole number of nights.

3. Run the query

Create registry.ts to register the module.

import { 
const createRegistry: <const Mods extends Record<string, object>, T = {
    currency: string;
}>(options: TypedOptions<{
    scope: {
        currency: string;
    };
}, Mods, T>) => Registry<{
    currency: string;
}, Mods, Record<string, never>, {}, AppError<`${string extends keyof Mods ? keyof Mods & string : (keyof Mods & string) | { [M in keyof Mods & string]: { [N in keyof Mods[M] & string]: Mods[M][N] extends Fn<Kind, any, any, any, any, any, infer Id extends string | undefined> ? `${M}.${Id extends string ? Id : N}` : never; }[keyof Mods[M] & string]; }[keyof Mods & string]}.forbidden`, undefined> | AppError<...> | AppError<...> | { [M in keyof Mods & string]: { [N in keyof Mods[M] & string]: Mods[M][N] extends ErrorDef<...> ? AppError<...> : never; }[keyof Mods[M] & string]; }[keyof Mods & string]>
Create the registry once at startup: `createRegistry({ modules, database, services })`.
createRegistry
} from "./logic";
import * as import pricingpricing from "./pricing"; export const
const registry: Registry<{
    currency: string;
}, {
    readonly pricing: typeof pricing;
}, Record<string, never>, {}, AppError<"pricing.forbidden" | "pricing.priceStay.forbidden", undefined> | AppError<"pricing.priceStay.invalidInput", {
    issues: {
        message: string;
        path?: PropertyKey[];
    }[];
}> | AppError<"pricing.notFound", undefined>>
registry
=
createRegistry<{
    readonly pricing: typeof pricing;
}, {
    currency: string;
}>(options: TypedOptions<{
    scope: {
        currency: string;
    };
}, {
    readonly pricing: typeof pricing;
}, {
    currency: string;
}>): Registry<{
    currency: string;
}, {
    readonly pricing: typeof pricing;
}, Record<string, never>, {}, AppError<"pricing.forbidden" | "pricing.priceStay.forbidden", undefined> | AppError<"pricing.priceStay.invalidInput", {
    issues: {
        message: string;
        path?: PropertyKey[];
    }[];
}> | AppError<...>>
createRegistry
({
modules: {
    readonly pricing: typeof pricing;
} & OwnModules<{
    scope: {
        currency: string;
    };
}, {
    readonly pricing: typeof pricing;
}>
One entry per module: `{ bookings, availability }` with `import * as bookings from "./bookings"`.
modules
: {
pricing: typeof pricing & {
    readonly priceStay: Fn<"query", {
        nights: number;
    }, {
        total: number;
        currency: string;
    }, false, {
        scope: {
            currency: string;
        };
    }, ZodObject<{
        nights: ZodNumber;
    }, $strip>, undefined>;
}
pricing
} });

Replace index.ts.

import { 
const priceStay: Fn<"query", {
    nights: number;
}, {
    total: number;
    currency: string;
}, false, {
    scope: {
        currency: string;
    };
}, ZodObject<{
    nights: ZodNumber;
}, $strip>, undefined>
priceStay
} from "./pricing";
import {
const registry: Registry<{
    currency: string;
}, {
    readonly pricing: typeof import("./pricing");
}, Record<string, never>, {}, AppError<"pricing.forbidden" | "pricing.priceStay.forbidden", undefined> | AppError<"pricing.priceStay.invalidInput", {
    issues: {
        message: string;
        path?: PropertyKey[];
    }[];
}> | AppError<"pricing.notFound", undefined>>
registry
} from "./registry";
const
const caller: Caller<{
    currency: string;
}, AppError<"pricing.forbidden" | "pricing.priceStay.forbidden", undefined> | AppError<"pricing.priceStay.invalidInput", {
    issues: {
        message: string;
        path?: PropertyKey[];
    }[];
}> | AppError<"pricing.notFound", undefined>>
caller
=
const registry: Registry<{
    currency: string;
}, {
    readonly pricing: typeof import("./pricing");
}, Record<string, never>, {}, AppError<"pricing.forbidden" | "pricing.priceStay.forbidden", undefined> | AppError<"pricing.priceStay.invalidInput", {
    issues: {
        message: string;
        path?: PropertyKey[];
    }[];
}> | AppError<"pricing.notFound", undefined>>
registry
.
Registry<{ currency: string; }, { readonly pricing: typeof import("./pricing"); }, Record<string, never>, {}, AppError<"pricing.forbidden" | "pricing.priceStay.forbidden", undefined> | AppError<...> | AppError<...>>.as(scope: {
    currency: string;
}): Caller<{
    currency: string;
}, AppError<"pricing.forbidden" | "pricing.priceStay.forbidden", undefined> | AppError<"pricing.priceStay.invalidInput", {
    issues: {
        message: string;
        path?: PropertyKey[];
    }[];
}> | AppError<"pricing.notFound", undefined>>
Bind who is calling, once per request, job or test: `const caller = registry.as(scope)`.
as
({ currency: stringcurrency: "EUR" });
const
const price: {
    total: number;
    currency: string;
}
price
= await
const caller: Caller<{
    currency: string;
}, AppError<"pricing.forbidden" | "pricing.priceStay.forbidden", undefined> | AppError<"pricing.priceStay.invalidInput", {
    issues: {
        message: string;
        path?: PropertyKey[];
    }[];
}> | AppError<"pricing.notFound", undefined>>
caller
.
CallerLike<{ currency: string; }>.run<Fn<"query", {
    nights: number;
}, {
    total: number;
    currency: string;
}, false, {
    scope: {
        currency: string;
    };
}, ZodObject<{
    nights: ZodNumber;
}, $strip>, undefined>>(fn: Fn<"query", {
    nights: number;
}, {
    total: number;
    currency: string;
}, false, {
    scope: {
        currency: string;
    };
}, ZodObject<{
    nights: ZodNumber;
}, $strip>, undefined>, input: {
    nights: number;
}, options?: RunOptions<{
    currency: string;
}> | undefined): Promise<{
    total: number;
    currency: string;
}>
Run any function as this caller: `await caller.run(bookings.cancel, input, { signal: request.signal })`.
run
(
const priceStay: Fn<"query", {
    nights: number;
}, {
    total: number;
    currency: string;
}, false, {
    scope: {
        currency: string;
    };
}, ZodObject<{
    nights: ZodNumber;
}, $strip>, undefined>
priceStay
, { nights: numbernights: 3 });
var console: Consoleconsole.Console.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(var JSON: JSON
An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
JSON
.JSON.stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string (+1 overload)
Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
@paramvalue A JavaScript value, usually an object or array, to be converted.@paramreplacer A function that transforms the results.@paramspace Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.@throws{TypeError} If a circular reference or a BigInt value is found.
stringify
(
const price: {
    total: number;
    currency: string;
}
price
));

Run bun index.ts. The terminal prints {"total":300,"currency":"EUR"}.

  • Module key. The key pricing gives the query its ID, pricing.priceStay.
  • Scope. registry.as sets the currency that reaches the query as ctx.scope.currency.

4. Test the query

Install Vitest.

bun add -d vitest

Create pricing.test.ts.

import { function afterEach<ExtraContext = object>(fn: AfterEachListener<ExtraContext>, timeout?: number): void
Registers a callback function to be executed after each test within the current suite has completed. This hook is useful for scenarios where you need to clean up or reset the test environment after each test runs, such as deleting temporary files, clearing test-specific database entries, or resetting mocked functions. **Note:** The `afterEach` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
@paramfn - The callback function to be executed after each test. This function receives an `TestContext` parameter if additional test context is needed.@paramtimeout - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.@returns@example```ts // Example of using afterEach to delete temporary files created during a test afterEach(async () => { await fileSystem.deleteTempFiles(); }); ```
afterEach
, function beforeEach<ExtraContext = object>(fn: BeforeEachListener<ExtraContext>, timeout?: number): void
Registers a callback function to be executed before each test within the current suite. This hook is useful for scenarios where you need to reset or reinitialize the test environment before each test runs, such as resetting database states, clearing caches, or reinitializing variables. **Note:** The `beforeEach` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file.
@paramfn - The callback function to be executed before each test. This function receives an `TestContext` parameter if additional test context is needed.@paramtimeout - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.@returns@example```ts // Example of using beforeEach to reset a database state beforeEach(async () => { await database.reset(); }); ```
beforeEach
, const expect: ExpectStaticexpect, const test: TestAPI
Defines a test case with a given name and test function. The test function can optionally be configured with test options.
@paramname - The name of the test or a function that will be used as a test name.@paramoptionsOrFn - Optional. The test options or the test function if no explicit name is provided.@paramoptionsOrTest - Optional. The test function or options, depending on the previous parameters.@throws{Error} If called inside another test function.@example```ts // Define a simple test test('should add two numbers', () => { expect(add(1, 2)).toBe(3); }); ```@example```ts // Define a test with options test('should subtract two numbers', { retry: 3 }, () => { expect(subtract(5, 2)).toBe(3); }); ```
test
} from "vitest";
import { function createTestRegistry<S extends object, Mods extends Record<string, object>, Cf, Sv, E>(registry: Registry<S, Mods, Cf, Sv, E>, options?: TestOptions<Cf, Sv>): TestRegistry<S, Mods, Cf, Sv, E>
Run each test inside a transaction that's rolled back, set up once with hooks: ```ts const t = createTestRegistry(registry); beforeEach(() => t.begin()); afterEach(() => t.rollback()); ``` Every top-level mutation inside becomes a savepoint, so a failing mutation rolls back just its own writes, like it would in production. Tests that share `t` run one at a time (one connection, nested savepoints).
createTestRegistry
} from "logic-sdk/testing";
import {
const registry: Registry<{
    currency: string;
}, {
    readonly pricing: typeof import("./pricing");
}, Record<string, never>, {}, AppError<"pricing.forbidden" | "pricing.priceStay.forbidden", undefined> | AppError<"pricing.priceStay.invalidInput", {
    issues: {
        message: string;
        path?: PropertyKey[];
    }[];
}> | AppError<"pricing.notFound", undefined>>
registry
} from "./registry";
import {
const priceStay: Fn<"query", {
    nights: number;
}, {
    total: number;
    currency: string;
}, false, {
    scope: {
        currency: string;
    };
}, ZodObject<{
    nights: ZodNumber;
}, $strip>, undefined>
priceStay
} from "./pricing";
const
const t: TestRegistry<{
    currency: string;
}, {
    readonly pricing: typeof import("./pricing");
}, Record<string, never>, {}, AppError<"pricing.forbidden" | "pricing.priceStay.forbidden", undefined> | AppError<"pricing.priceStay.invalidInput", {
    issues: {
        message: string;
        path?: PropertyKey[];
    }[];
}> | AppError<"pricing.notFound", undefined>>
t
=
createTestRegistry<{
    currency: string;
}, {
    readonly pricing: typeof import("./pricing");
}, Record<string, never>, {}, AppError<"pricing.forbidden" | "pricing.priceStay.forbidden", undefined> | AppError<"pricing.priceStay.invalidInput", {
    issues: {
        message: string;
        path?: PropertyKey[];
    }[];
}> | AppError<"pricing.notFound", undefined>>(registry: Registry<{
    currency: string;
}, {
    readonly pricing: typeof import("./pricing");
}, Record<string, never>, {}, AppError<"pricing.forbidden" | "pricing.priceStay.forbidden", undefined> | AppError<...> | AppError<...>>, options?: TestOptions<...> | undefined): TestRegistry<...>
Run each test inside a transaction that's rolled back, set up once with hooks: ```ts const t = createTestRegistry(registry); beforeEach(() => t.begin()); afterEach(() => t.rollback()); ``` Every top-level mutation inside becomes a savepoint, so a failing mutation rolls back just its own writes, like it would in production. Tests that share `t` run one at a time (one connection, nested savepoints).
createTestRegistry
(
const registry: Registry<{
    currency: string;
}, {
    readonly pricing: typeof import("./pricing");
}, Record<string, never>, {}, AppError<"pricing.forbidden" | "pricing.priceStay.forbidden", undefined> | AppError<"pricing.priceStay.invalidInput", {
    issues: {
        message: string;
        path?: PropertyKey[];
    }[];
}> | AppError<"pricing.notFound", undefined>>
registry
);
beforeEach<object>(fn: BeforeEachListener<object>, timeout?: number): void
Registers a callback function to be executed before each test within the current suite. This hook is useful for scenarios where you need to reset or reinitialize the test environment before each test runs, such as resetting database states, clearing caches, or reinitializing variables. **Note:** The `beforeEach` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file.
@paramfn - The callback function to be executed before each test. This function receives an `TestContext` parameter if additional test context is needed.@paramtimeout - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.@returns@example```ts // Example of using beforeEach to reset a database state beforeEach(async () => { await database.reset(); }); ```
beforeEach
(() =>
const t: TestRegistry<{
    currency: string;
}, {
    readonly pricing: typeof import("./pricing");
}, Record<string, never>, {}, AppError<"pricing.forbidden" | "pricing.priceStay.forbidden", undefined> | AppError<"pricing.priceStay.invalidInput", {
    issues: {
        message: string;
        path?: PropertyKey[];
    }[];
}> | AppError<"pricing.notFound", undefined>>
t
.TestRegistry<{ currency: string; }, { readonly pricing: typeof import("./pricing"); }, Record<string, never>, {}, AppError<"pricing.forbidden" | "pricing.priceStay.forbidden", undefined> | AppError<...> | AppError<...>>.begin(): Promise<void>
Open the test's transaction: `beforeEach(() => t.begin())`.
begin
());
afterEach<object>(fn: AfterEachListener<object>, timeout?: number): void
Registers a callback function to be executed after each test within the current suite has completed. This hook is useful for scenarios where you need to clean up or reset the test environment after each test runs, such as deleting temporary files, clearing test-specific database entries, or resetting mocked functions. **Note:** The `afterEach` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
@paramfn - The callback function to be executed after each test. This function receives an `TestContext` parameter if additional test context is needed.@paramtimeout - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.@returns@example```ts // Example of using afterEach to delete temporary files created during a test afterEach(async () => { await fileSystem.deleteTempFiles(); }); ```
afterEach
(() =>
const t: TestRegistry<{
    currency: string;
}, {
    readonly pricing: typeof import("./pricing");
}, Record<string, never>, {}, AppError<"pricing.forbidden" | "pricing.priceStay.forbidden", undefined> | AppError<"pricing.priceStay.invalidInput", {
    issues: {
        message: string;
        path?: PropertyKey[];
    }[];
}> | AppError<"pricing.notFound", undefined>>
t
.TestRegistry<{ currency: string; }, { readonly pricing: typeof import("./pricing"); }, Record<string, never>, {}, AppError<"pricing.forbidden" | "pricing.priceStay.forbidden", undefined> | AppError<...> | AppError<...>>.rollback(): Promise<void>
Roll it back: `afterEach(() => t.rollback())`.
rollback
());
test<object>(name: string | Function, fn?: TestFunction<object> | undefined, options?: number): void (+1 overload)
Defines a test case with a given name and test function. The test function can optionally be configured with test options.
@paramname - The name of the test or a function that will be used as a test name.@paramoptionsOrFn - Optional. The test options or the test function if no explicit name is provided.@paramoptionsOrTest - Optional. The test function or options, depending on the previous parameters.@throws{Error} If called inside another test function.@example```ts // Define a simple test test('should add two numbers', () => { expect(add(1, 2)).toBe(3); }); ```@example```ts // Define a test with options test('should subtract two numbers', { retry: 3 }, () => { expect(subtract(5, 2)).toBe(3); }); ```
test
("prices three nights in euros", async () => {
const
const caller: Caller<{
    currency: string;
}, AppError<"pricing.forbidden" | "pricing.priceStay.forbidden", undefined> | AppError<"pricing.priceStay.invalidInput", {
    issues: {
        message: string;
        path?: PropertyKey[];
    }[];
}> | AppError<"pricing.notFound", undefined>>
caller
=
const t: TestRegistry<{
    currency: string;
}, {
    readonly pricing: typeof import("./pricing");
}, Record<string, never>, {}, AppError<"pricing.forbidden" | "pricing.priceStay.forbidden", undefined> | AppError<"pricing.priceStay.invalidInput", {
    issues: {
        message: string;
        path?: PropertyKey[];
    }[];
}> | AppError<"pricing.notFound", undefined>>
t
.
TestRegistry<{ currency: string; }, { readonly pricing: typeof import("./pricing"); }, Record<string, never>, {}, AppError<"pricing.forbidden" | "pricing.priceStay.forbidden", undefined> | AppError<...> | AppError<...>>.as(scope: {
    currency: string;
}): Caller<{
    currency: string;
}, AppError<"pricing.forbidden" | "pricing.priceStay.forbidden", undefined> | AppError<"pricing.priceStay.invalidInput", {
    issues: {
        message: string;
        path?: PropertyKey[];
    }[];
}> | AppError<"pricing.notFound", undefined>>
Bind who is calling, like `registry.as(...)`. A listener that fails makes `run` throw, so a test can't pass over it.
as
({ currency: stringcurrency: "EUR" });
const
const price: {
    total: number;
    currency: string;
}
price
= await
const caller: Caller<{
    currency: string;
}, AppError<"pricing.forbidden" | "pricing.priceStay.forbidden", undefined> | AppError<"pricing.priceStay.invalidInput", {
    issues: {
        message: string;
        path?: PropertyKey[];
    }[];
}> | AppError<"pricing.notFound", undefined>>
caller
.
CallerLike<{ currency: string; }>.run<Fn<"query", {
    nights: number;
}, {
    total: number;
    currency: string;
}, false, {
    scope: {
        currency: string;
    };
}, ZodObject<{
    nights: ZodNumber;
}, $strip>, undefined>>(fn: Fn<"query", {
    nights: number;
}, {
    total: number;
    currency: string;
}, false, {
    scope: {
        currency: string;
    };
}, ZodObject<{
    nights: ZodNumber;
}, $strip>, undefined>, input: {
    nights: number;
}, options?: RunOptions<{
    currency: string;
}> | undefined): Promise<{
    total: number;
    currency: string;
}>
Run any function as this caller: `await caller.run(bookings.cancel, input, { signal: request.signal })`.
run
(
const priceStay: Fn<"query", {
    nights: number;
}, {
    total: number;
    currency: string;
}, false, {
    scope: {
        currency: string;
    };
}, ZodObject<{
    nights: ZodNumber;
}, $strip>, undefined>
priceStay
, { nights: numbernights: 3 });
expect<{
    total: number;
    currency: string;
}>(actual: {
    total: number;
    currency: string;
}, message?: string): Assertion<void, {
    total: number;
    currency: string;
}> (+1 overload)
expect
(
const price: {
    total: number;
    currency: string;
}
price
).
JestAssertion<void, { total: number; currency: string; }>.toEqual: <{
    total: number;
    currency: string;
}>(expected: {
    total: number;
    currency: string;
}) => void
Used when you want to check that two objects have the same value. This matcher recursively checks the equality of all fields, rather than checking for object identity.
@exampleexpect(user).toEqual({ name: 'Alice', age: 30 });
toEqual
({ total: numbertotal: 300, currency: stringcurrency: "EUR" });
});

Run bunx vitest run. The terminal reports one passing test.

See also

Was this page helpful?