@kovojs/test
Generated from 8 public subpaths — 75 exports, 75 documented. Do not edit by hand.
@kovojs/test/assertions#
Task: Mutation failure assertions and optimistic property testing helpers.
Source: packages/test/src/assertions.ts
Values#
assertMutationError#
Assert that a mutation result is a typed failure with the expected code (and, optionally, payload), returning the typed payload for further assertions. Throws with a descriptive message on mismatch (SPEC §10.3).
| Parameter | Type | Description |
|---|---|---|
mutation |
MutationDefinition<Key, InputSchema, Errors, Request, Value> |
The mutation whose result is being checked (for typing and messages). |
result |
MutationResult<Value> |
The MutationResult to assert against. |
expected |
MutationErrorExpectation<Errors, Code> |
The expected error code, or { code, payload }. |
| (returns) | InferSchema<Errors[Code]> |
The typed error payload. |
Signature
function assertMutationError<
const Key extends string,
InputSchema extends Schema<unknown>,
Errors extends Record<string, Schema<unknown>>,
Request,
Value,
const Code extends Extract<keyof Errors, string>,
>(
mutation: MutationDefinition<Key, InputSchema, Errors, Request, Value>,
result: MutationResult<Value>,
expected: MutationErrorExpectation<Errors, Code>,
): InferSchema<Errors[Code]>;propertyTest#
Property-check that an optimistic prediction matches the eventual server
result across many cases. For each case it runs predict and the real
apply, projects both with shape, and throws on the first divergence —
proving the optimistic transform is sound (SPEC §10.4).
| Parameter | Type | Description |
|---|---|---|
options |
PropertyTestOptions<State, Input, ClientShape> |
The predict, apply, cases, and optional shape projection. |
| (returns) | PropertyTestResult |
A PropertyTestResult with the number of cases run. |
Copyable example
import { propertyTest } from '@kovojs/test/assertions';
type Cart = { count: number };
const result = propertyTest<Cart, { quantity: number }>({
apply: (state, input) => ({ count: state.count + input.quantity }),
predict: (state, input) => ({ count: state.count + input.quantity }),
cases: [{ state: { count: 0 }, input: { quantity: 2 } }],
});
// result.cases === 1Signature
function propertyTest<State, Input, ClientShape = State>(
options: PropertyTestOptions<State, Input, ClientShape>,
): PropertyTestResult;Supporting types#
MutationErrorExpectation#
An expected mutation failure: a code, or a code with an expected payload.
Signature
type MutationErrorExpectation<
Errors extends Record<string, Schema<unknown>>,
Code extends Extract<keyof Errors, string>,
> =
| Code
| {
code: Code;
payload?: InferSchema<Errors[Code]>;
};PropertyCase#
One property-test case: an initial state and the mutation input to apply.
Signature
interface PropertyCase<State, Input> {
input: Input;
state: State;
}PropertyTestOptions#
Options for propertyTest: the optimistic predict, the eventual apply, the cases, and an optional shape projection.
Signature
interface PropertyTestOptions<State, Input, ClientShape = unknown> {
apply: (state: State, input: Input) => State;
cases: Iterable<PropertyCase<State, Input>>;
predict: (state: State, input: Input) => ClientShape;
shape?: (state: State) => ClientShape;
}PropertyTestResult#
The result of propertyTest: how many cases ran.
Signature
interface PropertyTestResult {
cases: number;
}@kovojs/test/csrf#
Task: Mutation-bound CSRF tokens for focused synthetic request tests.
Source: packages/test/src/csrf.ts
Values#
mutationCsrfTokenForTesting#
Mint a mutation-bound CSRF token for a synthetic request-level test.
Prefer rendering the real form and reading its hidden field for an end-to-end assertion. This helper is for focused request tests that intentionally bypass form rendering (SPEC §§9.1, 12).
| Parameter | Type | Description |
|---|---|---|
request |
Request |
Synthetic request fixture used by the app's CSRF policy. |
options |
CsrfOptions<Request> |
The same CSRF options configured by the app. |
context |
{ mutation: string | { readonly key: string } } |
Exact mutation handle or derived mutation key. |
| (returns) | string |
A token accepted only for that mutation audience. |
Signature
function mutationCsrfTokenForTesting<Request>(
request: Request,
options: CsrfOptions<Request>,
context: { mutation: string | { readonly key: string } },
): string;@kovojs/test/headers#
Task: Header helpers for app scenario tests.
Source: packages/test/src/headers.ts
Values#
headerValues#
Read all values for header name from a Headers or {@link HeaderRecord}, case-insensitively (handles set-cookie).
Signature
function headerValues(source: Headers | HeaderRecord | undefined, name: string): string[];setCookieValues#
Read all set-cookie header values from a Headers or {@link HeaderRecord}.
Signature
function setCookieValues(source: Headers | HeaderRecord | undefined): string[];cookiePair#
Return the name=value pair of a raw set-cookie string (drops attributes).
Signature
function cookiePair(setCookie: string | undefined): string;firstSetCookiePair#
Return the name=value pair of the first set-cookie on a Headers or {@link HeaderRecord}.
Signature
function firstSetCookiePair(source: Headers | HeaderRecord | undefined): string;decodeFrameworkIdentityToken#
Decode one canonical framework identity token captured from rendered test HTML.
This test-only helper lets scenario suites inspect kovo-deps without depending on Kovo's
internal wire-codec subpath (SPEC.md §9.1).
Signature
function decodeFrameworkIdentityToken(value: unknown): string | undefined;enhancedMutationHeaders#
Build the enhanced-mutation request headers used by app scenario tests (SPEC.md §9.1).
Signature
function enhancedMutationHeaders(
options: EnhancedMutationHeaderOptions = {},
): Record<string, string>;Supporting types#
HeaderRecord#
A plain header bag accepted by the header helpers alongside a Headers instance.
Signature
type HeaderRecord = Record<string, string | string[] | undefined>;EnhancedMutationTarget#
Structured mutation target selection for enhanced scenario requests.
Signature
interface EnhancedMutationTarget {
queries?: readonly string[] | string;
target: string;
}EnhancedMutationLiveTarget#
Structured live-target descriptor for enhanced scenario requests.
Signature
interface EnhancedMutationLiveTarget {
attestation: string;
component: string;
props?: Record<string, unknown>;
target: string;
}EnhancedMutationHeaderOptions#
Options for {@link enhancedMutationHeaders}; targets follow the mutation wire protocol in SPEC.md §9.1.
Signature
interface EnhancedMutationHeaderOptions {
formTarget?: string;
liveTargets?: readonly (EnhancedMutationLiveTarget | string)[] | string;
targets?: readonly (EnhancedMutationTarget | string)[] | string;
}@kovojs/test/harness#
Task: App-inferred mutation, query, route, request, and DB harness bound to a verified build artifact.
Source: packages/test/src/harness.ts
Values#
createKovoTestHarness#
Create an app-scoped test harness.
TypeScript obtains mutation/query/route/request/DB contracts from app; runtime coverage facts
come only from the explicitly selected, completion- and digest-verified build graph. A stale,
partial, failed-build, or wrong-app artifact rejects before the returned context can run one
handler (SPEC §§5.2.4, 11, and 12).
Signature
async function createKovoTestHarness<App extends KovoApp>(
app: App,
options: KovoTestHarnessOptions<App>,
): Promise<KovoTestContext<App>>;Supporting types#
PageAssertion#
Rendered page returned by {@link KovoTestContext.page}.
Signature
interface PageAssertion {
/** Extract one named Kovo fragment from the full rendered response. */
fragment(target: string): string;
/** Full rendered response body. */
html: string;
}DbVerificationDiagnostic#
Graph-honesty diagnostic observed while a harness executes database operations.
Signature
interface DbVerificationDiagnostic extends RegisteredDiagnostic<DiagnosticCode> {
/** Static branch label when the diagnostic is branch-specific. */
branch?: string;
/** Declared or observed application data domain. */
domain: string;
/** Authored source site when retained by build evidence. */
site?: string;
}KovoTestDb#
Database contract retained by the imported opaque app.
Signature
type KovoTestDb<App extends KovoApp> =
InferKovoAppTypes<App> extends { readonly db: infer Db } ? Db : never;KovoTestRequest#
Request contract retained by the imported opaque app after provider inference.
Signature
type KovoTestRequest<App extends KovoApp> =
InferKovoAppTypes<App> extends { readonly request: infer Request } ? Request : never;KovoTestRawRequest#
Raw request contract accepted by the imported app's custom-adapter boundary.
Signature
type KovoTestRawRequest<App extends KovoApp> =
InferKovoAppTypes<App> extends { readonly rawRequest: infer Request }
? Request
: globalThis.Request;KovoTestMutation#
Exact mutation-handle union assembled into the imported app.
Signature
type KovoTestMutation<App extends KovoApp> =
InferKovoAppTypes<App> extends {
readonly declarations: { readonly mutation: infer Mutation };
}
? Mutation
: never;KovoTestQuery#
Exact query-handle union assembled into the imported app.
Signature
type KovoTestQuery<App extends KovoApp> =
InferKovoAppTypes<App> extends {
readonly declarations: { readonly query: infer Query };
}
? Query
: never;KovoTestRouteKey#
Exact route-key union assembled into the imported app.
Signature
type KovoTestRouteKey<App extends KovoApp> =
InferKovoAppTypes<App> extends {
readonly declarations: { readonly route: infer Route };
}
? Route extends RouteHandle<infer Path, infer _Owner>
? Path
: never
: never;KovoTestMutationInput#
Input inferred from one app-scoped mutation handle.
Signature
type KovoTestMutationInput<Mutation> =
Mutation extends MutationHandle<infer Input, infer _Value, infer _Errors, infer _Owner>
? Input
: never;KovoTestMutationValue#
Successful value inferred from one app-scoped mutation handle.
Signature
type KovoTestMutationValue<Mutation> =
Mutation extends MutationHandle<infer _Input, infer Value, infer _Errors, infer _Owner>
? Value
: never;KovoTestMutationError#
Declared application-error union inferred from one app-scoped mutation handle.
Signature
type KovoTestMutationError<Mutation> =
Mutation extends MutationHandle<infer _Input, infer _Value, infer Errors, infer _Owner>
? {
[Code in Extract<keyof Errors, string>]: MutationFail<Code, InferSchema<Errors[Code]>>;
}[Extract<keyof Errors, string>]
: never;KovoTestFrameworkMutationError#
Framework-owned mutation failures that can precede an app handler.
Signature
type KovoTestFrameworkMutationError =
| MutationFail<'CSRF', Record<never, never>>
| MutationFail<'RATE_LIMITED', unknown>
| MutationFail<'STALE_VERSION', Record<never, never>>
| MutationFail<'UNAUTHORIZED', unknown>
| MutationFail<'VALIDATION', ValidationFailurePayload>;KovoTestMutationResult#
Structured result inferred from one app-scoped mutation handle.
Signature
type KovoTestMutationResult<Mutation> =
| KovoTestFrameworkMutationError
| KovoTestMutationError<Mutation>
| MutationSuccess<KovoTestMutationValue<Mutation>, KovoTestMutationInput<Mutation>>;KovoTestQueryInput#
Input inferred from one app-scoped query handle.
Signature
type KovoTestQueryInput<Query> =
Query extends QueryHandle<infer Input, infer _Value, infer _Owner> ? Input : never;KovoTestQueryResult#
Result inferred from one app-scoped query handle.
Signature
type KovoTestQueryResult<Query> =
Query extends QueryHandle<infer _Input, infer Value, infer _Owner> ? Awaited<Value> : never;KovoTestVerificationConfig#
Runtime SQL-observation config; static graph facts always come from the verified artifact.
Signature
interface KovoTestVerificationConfig {
domainByTable: Record<string, string>;
exemptTables?: readonly string[];
keyByTable?: Record<string, string>;
sqlDialect?: 'postgres' | 'sqlite';
}KovoTestHarnessOptions#
Explicit artifact and runtime fixtures for one imported app contract.
Signature
interface KovoTestHarnessOptions<App extends KovoApp> {
/**
* Exact successful-build graph to consume. Relative paths are rejected so tests cannot
* accidentally trust a nearby artifact (SPEC §§5.2.4 and 12).
*/
artifact: string | URL;
/** Absolute project root used to re-hash every analyzed source/config input. */
projectRoot: string | URL;
/**
* Explicit origin of a separately bootstrapped app used by `page()` and `request()`.
* Direct `query()` and `exec()` tests do not require it.
*/
baseUrl?: string | URL;
/** Optional test DB whose type is inferred from the imported app contract. */
db?: KovoTestDb<App>;
/** Typed provider/request fixture merged into direct query and mutation execution. */
request?: Partial<Omit<KovoTestRequest<App>, 'db'>>;
/**
* Runtime adapter mapping used by SQL observation. Touch/read facts cannot be supplied here;
* those come only from the verified build graph.
*/
verification?: KovoTestVerificationConfig;
}KovoTestExecOptions#
Options for one direct app-scoped mutation execution.
Signature
interface KovoTestExecOptions<App extends KovoApp> {
csrf?: CsrfOptions<KovoTestRequest<App>>;
request?: Partial<Omit<KovoTestRequest<App>, 'db'>>;
}KovoTestContext#
App-scoped harness whose callable surface is inferred from one imported opaque app.
Signature
interface KovoTestContext<App extends KovoApp> {
readonly db: KovoTestDb<App> | undefined;
exec<Mutation extends KovoTestMutation<App>>(
mutation: Mutation,
input: KovoTestMutationInput<Mutation>,
options?: KovoTestExecOptions<App>,
): Promise<KovoTestMutationResult<Mutation>>;
page(path: KovoTestRouteKey<App>, init?: Omit<RequestInit, 'method'>): Promise<PageAssertion>;
query<Query extends KovoTestQuery<App>>(
query: Query,
...input: [KovoTestQueryInput<Query>] extends [undefined]
? [input?: undefined]
: [input: KovoTestQueryInput<Query>]
): Promise<KovoTestQueryResult<Query>>;
request(request: KovoTestRawRequest<App>): Promise<Response>;
verificationDiagnostics(): readonly DbVerificationDiagnostic[];
}@kovojs/test/html-fragment#
Task: HTML and Kovo fragment fact extractors for scenario assertions.
Source: packages/test/src/html-fragment.ts
Values#
fragmentHtml#
Extracts the server-rendered HTML for a single fragment target from a page
response, backing the page().fragment(target) scenario assertion (SPEC.md
§12). Returns the inner HTML of an explicit <kovo-fragment target="…">
envelope when present, otherwise the full markup of the stamped target element
resolved by id/kovo-fragment-target (SPEC.md §9.1); returns '' when no
matching target is found.
| Parameter | Type | Description |
|---|---|---|
html |
string |
The full page or fragment-response HTML to search. |
target |
string |
The fragment target name to resolve. |
| (returns) | string |
The target's HTML, or '' when no matching target exists. |
Signature
function fragmentHtml(html: string, target: string): string;htmlElementCount#
Counts the elements in html matching selector, a convenience over
{@link htmlElementFacts} for scenario assertions (SPEC.md §12).
| Parameter | Type | Description |
|---|---|---|
html |
string |
The HTML to scan. |
selector |
HtmlElementSelector |
Tag/attribute filter; an empty selector matches every element. |
| (returns) | number |
The number of matching elements. |
Signature
function htmlElementCount(html: string, selector: HtmlElementSelector = {}): number;htmlElementFacts#
Parses html and returns a {@link HtmlElementFact} for every element matching
selector, the core extractor underlying the other fact helpers for
browser-free scenario assertions (SPEC.md §12).
| Parameter | Type | Description |
|---|---|---|
html |
string |
The HTML to scan. |
selector |
HtmlElementSelector |
Tag/attribute filter; an empty selector matches every element. |
| (returns) | HtmlElementFact[] |
Facts for every matching element, in document order. |
Signature
function htmlElementFacts(
html: string,
selector: HtmlElementSelector = {},
): HtmlElementFact[];htmlDocumentFacts#
Extracts document-level facts from a full page response for scenario
assertions (SPEC.md §12): body attributes, decoded inline JSON scripts (SPEC.md
§9.1), <link>/<meta> facts, body text, and the title.
| Parameter | Type | Description |
|---|---|---|
html |
string |
The full page HTML. |
| (returns) | HtmlDocumentFact |
The aggregated {@link HtmlDocumentFact}. |
Signature
function htmlDocumentFacts(html: string): HtmlDocumentFact;htmlLinkHrefs#
Collects the non-empty href values of <link> elements matching the given
attribute filter, for asserting document link targets (SPEC.md §12).
| Parameter | Type | Description |
|---|---|---|
html |
string |
The HTML to scan. |
attrs |
Record<string, string | true> |
Attribute filter applied to candidate <link> elements. |
| (returns) | string[] |
The matching links' href values, in document order. |
Signature
function htmlLinkHrefs(html: string, attrs: Record<string, string | true> = {}): string[];kovoQueryJsonValues#
Returns the decoded JSON values carried by <kovo-query name="…"> wire
envelopes (SPEC.md §9.1) for the given query name, for asserting query payloads
in scenario tests (SPEC.md §12).
| Parameter | Type | Description |
|---|---|---|
html |
string |
The page or fragment-response HTML. |
name |
string |
The <kovo-query> name to read. |
| (returns) | unknown[] |
The decoded JSON values for that name, or an empty array when absent. |
Signature
function kovoQueryJsonValues(html: string, name: string): unknown[];htmlFormFacts#
Extracts a {@link HtmlFormFact} for every <form> in html, including its
named control fields, for browser-free form scenario assertions (SPEC.md §12).
| Parameter | Type | Description |
|---|---|---|
html |
string |
The page HTML to scan. |
| (returns) | HtmlFormFact[] |
Facts for every form, in document order. |
Signature
function htmlFormFacts(html: string): HtmlFormFact[];htmlFormActions#
Returns the resolved action of every <form> in html, for asserting form
submission targets in scenario tests (SPEC.md §12).
| Parameter | Type | Description |
|---|---|---|
html |
string |
The page HTML to scan. |
| (returns) | string[] |
Each form's action, in document order. |
Signature
function htmlFormActions(html: string): string[];htmlFormFields#
Flattens the named control fields across every <form> in html, optionally
filtered to a single field name, for form-field scenario assertions (SPEC.md
§12).
| Parameter | Type | Description |
|---|---|---|
html |
string |
The page HTML to scan. |
name |
string |
When provided, restricts results to fields with this name. |
| (returns) | HtmlFormFieldFact[] |
The matching field facts, in document order. |
Signature
function htmlFormFields(html: string, name?: string): HtmlFormFieldFact[];htmlFormFieldsByName#
Indexes a form's fields by their name, for keyed lookup in scenario
assertions (SPEC.md §12). Returns an empty map when form is undefined; later
fields win on duplicate names.
| Parameter | Type | Description |
|---|---|---|
form |
HtmlFormFact | undefined |
The form fact whose fields to index, or undefined. |
| (returns) | Record<string, HtmlFormFieldFact> |
A map from field name to {@link HtmlFormFieldFact}. |
Signature
function htmlFormFieldsByName(
form: HtmlFormFact | undefined,
): Record<string, HtmlFormFieldFact>;htmlKeyFacts#
Extracts a {@link HtmlKeyFact} for every element carrying a kovo-key runtime
identity (SPEC.md §13.2), optionally filtered to a single key, for keyed-row
scenario assertions (SPEC.md §12).
| Parameter | Type | Description |
|---|---|---|
html |
string |
The page or fragment HTML to scan. |
key |
string |
When provided, restricts results to elements with this kovo-key. |
| (returns) | HtmlKeyFact[] |
The matching key facts, in document order. |
Signature
function htmlKeyFacts(html: string, key?: string): HtmlKeyFact[];htmlKeyValues#
Returns the kovo-key value (SPEC.md §13.2) of every keyed element in html,
for asserting the set and order of keyed rows in scenario tests (SPEC.md §12).
| Parameter | Type | Description |
|---|---|---|
html |
string |
The page or fragment HTML to scan. |
| (returns) | string[] |
Each keyed element's kovo-key, in document order. |
Signature
function htmlKeyValues(html: string): string[];htmlKeyTextMap#
Maps each keyed element's kovo-key (SPEC.md §13.2) to its collapsed text
content, for asserting rendered text per keyed row in scenario tests (SPEC.md
§12). On duplicate keys, the later element's text wins.
| Parameter | Type | Description |
|---|---|---|
html |
string |
The page or fragment HTML to scan. |
| (returns) | Record<string, string> |
A map from kovo-key to that element's text content. |
Signature
function htmlKeyTextMap(html: string): Record<string, string>;htmlTextContent#
Strips tags from html, decodes HTML entities, and collapses whitespace to
single spaces (trimmed), yielding the visible text for content scenario
assertions (SPEC.md §12).
| Parameter | Type | Description |
|---|---|---|
html |
string |
The HTML fragment to reduce to text. |
| (returns) | string |
The decoded, whitespace-collapsed text content. |
Signature
function htmlTextContent(html: string): string;Supporting types#
HtmlElementFact#
One matched HTML element extracted from a page or fragment response, used to assert against server-rendered markup without a browser (SPEC.md §12). Holds the element's lowercased attribute map, its full outer markup, its inner content, and its lowercased tag name.
Signature
interface HtmlElementFact {
attrs: Record<string, string>;
html: string;
innerHtml: string;
tag: string;
}HtmlElementSelector#
Selector for filtering elements in {@link htmlElementFacts} and related
extractors (SPEC.md §12). tag matches a lowercased tag name; each attrs
entry requires that attribute to be present, with true asserting presence
only and a string asserting an exact value.
Signature
interface HtmlElementSelector {
attrs?: Record<string, string | true>;
tag?: string;
}HtmlJsonScriptFact#
One decoded JSON script found in a server-rendered document (SPEC.md §9.1, §12).
Signature
interface HtmlJsonScriptFact {
attrs: Record<string, string>;
html: string;
json: unknown;
rawJson: string;
}HtmlDocumentFact#
Document-level facts extracted from a full page response for scenario
assertions (SPEC.md §12): the <body> attribute map, decoded inline JSON
script payloads (SPEC.md §9.1), all <link> and <meta> element facts, the
body's collapsed text content, and the document title.
Signature
interface HtmlDocumentFact {
bodyAttrs: Record<string, string>;
jsonScripts: HtmlJsonScriptFact[];
links: HtmlElementFact[];
metas: HtmlElementFact[];
text: string;
title: string;
}HtmlFormFieldFact#
One named form control (button, input, select, or textarea) extracted
from a rendered form for scenario assertions (SPEC.md §12). Carries the
control's attribute map, outer markup, name, lowercased tag, type, and
value (falling back to inner content when no value attribute is set).
Signature
interface HtmlFormFieldFact {
attrs: Record<string, string>;
html: string;
name: string;
tag: string;
type: string;
value: string;
}HtmlFormFact#
One <form> extracted from a page response for scenario assertions (SPEC.md
§12): its resolved action, attribute map, named field facts, outer and inner
markup, and method (defaulting to get).
Signature
interface HtmlFormFact {
action: string;
attrs: Record<string, string>;
fields: HtmlFormFieldFact[];
html: string;
innerHtml: string;
method: string;
}HtmlKeyFact#
One element carrying a kovo-key runtime identity (SPEC.md §13.2), extracted
for keyed-row scenario assertions (SPEC.md §12). Holds the element's attribute
map, outer and inner markup, the kovo-key value, lowercased tag, and its
collapsed text content.
Signature
interface HtmlKeyFact {
attrs: Record<string, string>;
html: string;
innerHtml: string;
key: string;
tag: string;
text: string;
}@kovojs/test/pglite#
Task: PGlite-backed test database helpers.
Source: packages/test/src/pglite.ts
Values#
createPgliteTestDb#
Spin up an ephemeral in-process Postgres (PGlite) for tests, returning a handle with SQL and row helpers. No external database required.
| Parameter | Type | Description |
|---|---|---|
options |
PGliteOptions |
PGlite options (e.g. data directory; defaults to in-memory). |
| (returns) | Promise<PgliteTestDb> |
A ready PgliteTestDb. |
Signature
async function createPgliteTestDb(options: PGliteOptions = {}): Promise<PgliteTestDb>;Supporting types#
PgliteStatementCarrier#
SQL statement object accepted by PgliteTestDb helpers.
Signature
interface PgliteStatementCarrier {
/** Drizzle SQL chunks, used by Kovo static/parameterized SQL objects. */
queryChunks?: readonly unknown[];
/** SQL text, matching common driver carrier shape. */
sql?: string;
/** SQL text, matching common driver carrier shape. */
text?: string;
/** Bound statement values. */
values?: readonly unknown[];
}PgliteStatementInput#
SQL statement input accepted by PgliteTestDb helpers.
Signature
type PgliteStatementInput = string | PgliteStatementCarrier;PgliteTestDb#
A PGlite-backed test database handle: exec/query SQL helpers plus read/write and close.
Signature
interface PgliteTestDb {
close(): Promise<void>;
exec(statement: PgliteStatementInput): Promise<Results[]>;
pglite: PGlite;
query<Row extends Record<string, unknown> = Record<string, unknown>>(
statement: PgliteStatementInput,
params?: readonly unknown[],
): Promise<Row[]>;
read<Row extends Record<string, unknown> = Record<string, unknown>>(
table: string,
): Promise<Row[]>;
write(table: string, value: Record<string, unknown>): Promise<void>;
}@kovojs/test/postgres#
Task: PGlite-backed Postgres RLS helpers with owner, admin, and system postures.
Source: packages/test/src/postgres.ts
Values#
createPostgresTestRuntime#
Provision an ephemeral PGlite-backed Kovo Postgres runtime for RLS tests.
This is the canonical app-facing home for the testing capability. It exercises the same
principal, reader, admin, and system paths as the server runtime without exposing a parallel
@kovojs/server/testing API (SPEC §§10.3, 12).
Signature
async function createPostgresTestRuntime(
options: KovoPostgresTestRuntimeOptions,
): Promise<KovoPostgresTestRuntime>;Supporting types#
KovoPostgresTestDb#
Drizzle database handle passed to owner-scoped Postgres test callbacks.
Signature
type KovoPostgresTestDb = KovoPostgresRuntimeDb;KovoPostgresTestAdminDb#
Read-only Postgres handle passed to admin-guarded test callbacks.
The runtime is the same fail-closed reader capability used by Kovo request paths. This public shape deliberately omits write verbs while preserving Drizzle reads and the two reviewed raw read escape hatches (SPEC §§10.3, 12).
Signature
type KovoPostgresTestAdminDb = Pick<
KovoPostgresRuntimeDb,
Extract<keyof KovoPostgresRuntimeDb, '$count' | '$with' | 'query' | 'select' | 'selectDistinct'>
> & {
crossOwnerRead<Row = unknown>(
statement: unknown,
declaration: CrossOwnerReadDeclaration,
): Promise<Row[]> | Row[];
rawRead<Row = unknown>(
statement: unknown,
declaration: RawReadDeclaration,
): Promise<Row[]> | Row[];
};KovoPostgresTestSystemDb#
Drizzle database handle passed to audited non-request system test callbacks.
Signature
type KovoPostgresTestSystemDb = KovoPostgresRuntimeDb;KovoPostgresTestRuntimeOptions#
Configuration for an ephemeral owner-scoped Postgres test runtime.
Signature
interface KovoPostgresTestRuntimeOptions {
/**
* Physical owner/authz tables allowed through the audited admin cross-owner read path.
* Each test must opt in per table (SPEC §10.3 DEC-G).
*/
crossOwnerReadTables?: readonly string[];
/** App schema module, normally `import * as schema from '../src/schema.js'`. */
schema: Record<string, unknown>;
/** SQL run after the ephemeral PGlite schema is provisioned. */
seedSql?: string | readonly string[];
}KovoPostgresTestRuntime#
Ephemeral PGlite-backed runtime that exercises Kovo's real Postgres RLS posture.
Signature
interface KovoPostgresTestRuntime {
/** Temporary data directory removed by {@link close}. */
readonly dataDir: string;
/** Release the runtime and remove its temporary data. */
close(): Promise<void>;
/** Run with one owner principal through Kovo's request-scoped database capability. */
withPrincipal<Result>(
principalId: string,
callback: (db: KovoPostgresTestDb) => Result | Promise<Result>,
): Promise<Result>;
/** Run an explicitly table-scoped, admin-guarded cross-owner read. */
asAdmin<Result>(
principalId: string,
callback: (db: KovoPostgresTestAdminDb) => Result | Promise<Result>,
): Promise<Result>;
/** Run audited non-request system work with a required non-empty reason. */
asSystem<Result>(
reason: string,
callback: (db: KovoPostgresTestSystemDb) => Result | Promise<Result>,
): Promise<Result>;
}@kovojs/test/sqlite#
Task: SQLite-backed test database helpers.
Source: packages/test/src/sqlite.ts
Values#
createSqliteTestDb#
Spin up an ephemeral in-process SQLite database for tests. The default driver
is better-sqlite3, matching the SQLite runtime slice in plans/sqlite-support.md.
| Parameter | Type | Description |
|---|---|---|
options |
SqliteTestDbOptions |
better-sqlite3 options. |
| (returns) | SqliteTestDb |
A ready SqliteTestDb. |
Signature
function createSqliteTestDb(options: SqliteTestDbOptions = {}): SqliteTestDb;Supporting types#
SqliteStatementCarrier#
SQL statement object accepted by SqliteTestDb helpers.
Signature
interface SqliteStatementCarrier {
/** SQL text, matching common driver carrier shape. */
sql?: string;
/** SQL text, matching common driver carrier shape. */
text?: string;
/** Bound statement values. */
values?: readonly unknown[];
}SqliteStatementInput#
SQL statement input accepted by SqliteTestDb helpers.
Signature
type SqliteStatementInput = string | SqliteStatementCarrier;SqliteNativeStatement#
Minimal better-sqlite3 statement handle surfaced by SqliteTestDb.sqlite.
Signature
interface SqliteNativeStatement<Row = unknown> {
all(...params: unknown[]): Row[];
run(...params: unknown[]): unknown;
}SqliteNativeHandle#
Minimal better-sqlite3 database handle surfaced by SqliteTestDb.sqlite.
Signature
interface SqliteNativeHandle {
close(): void;
exec(statement: string): unknown;
prepare<Row = unknown>(statement: string): SqliteNativeStatement<Row>;
transaction<Callback extends (...args: never[]) => unknown>(callback: Callback): Callback;
}SqliteTestDbOptions#
Options passed through to the better-sqlite3 constructor used by createSqliteTestDb().
Signature
interface SqliteTestDbOptions {
/** Database filename. Defaults to ':memory:'. Use a real file to enable a dedicated read-only reader connection. */
filename?: string;
/** Require the database file to already exist before opening it. */
fileMustExist?: boolean;
/** Path to a custom better-sqlite3 native binding. */
nativeBinding?: string;
/** Open the database in read-only mode. */
readonly?: boolean;
/** Busy timeout in milliseconds. */
timeout?: number;
/** Optional SQL statement logger. */
verbose?: (message?: unknown, ...additionalArgs: unknown[]) => void;
}SqliteTestDb#
A better-sqlite3-backed test database handle: raw SQLite plus SQL and row helpers.
Signature
interface SqliteTestDb {
close(): void;
exec(statement: SqliteStatementInput): void;
query<Row extends Record<string, unknown> = Record<string, unknown>>(
statement: SqliteStatementInput,
params?: readonly unknown[],
): Row[];
read<Row extends Record<string, unknown> = Record<string, unknown>>(table: string): Row[];
sqlite: SqliteNativeHandle;
write(table: string, value: Record<string, unknown>): void;
}