---
title: "@kovojs/test"
description: App-scoped test harness, digest-verified graph checks, and explicit database-engine helpers.
order: 4
---

# @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`](https://github.com/kovojs/kovo/blob/main/packages/test/src/assertions.ts)

### Values

#### `assertMutationError` {#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` | <code><a href="/api/server/#mutationdefinition">MutationDefinition</a>&lt;Key, InputSchema, Errors, Request, Value&gt;</code> | The mutation whose result is being checked (for typing and messages). |
| `result` | <code><a href="/api/server/#mutationresult">MutationResult</a>&lt;Value&gt;</code> | The `MutationResult` to assert against. |
| `expected` | <code><a href="#mutationerrorexpectation">MutationErrorExpectation</a>&lt;Errors, Code&gt;</code> | The expected error code, or `{ code, payload }`. |
| *(returns)* | <code><a href="/api/server/#inferschema">InferSchema</a>&lt;Errors[Code]&gt;</code> | The typed error payload. |

**Signature**

```ts
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` {#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` | <code><a href="#propertytestoptions">PropertyTestOptions</a>&lt;State, Input, ClientShape&gt;</code> | The `predict`, `apply`, `cases`, and optional `shape` projection. |
| *(returns)* | <code><a href="#propertytestresult">PropertyTestResult</a></code> | A `PropertyTestResult` with the number of cases run. |

**Copyable example**

```ts
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 === 1
```

**Signature**

```ts
function propertyTest<State, Input, ClientShape = State>(
  options: PropertyTestOptions<State, Input, ClientShape>,
): PropertyTestResult;
```

### Supporting types

#### `MutationErrorExpectation` {#mutationerrorexpectation}

An expected mutation failure: a code, or a code with an expected payload.

**Signature**

```ts
type MutationErrorExpectation<
  Errors extends Record<string, Schema<unknown>>,
  Code extends Extract<keyof Errors, string>,
> =
  | Code
  | {
      code: Code;
      payload?: InferSchema<Errors[Code]>;
    };
```

#### `PropertyCase` {#propertycase}

One property-test case: an initial `state` and the mutation `input` to apply.

**Signature**

```ts
interface PropertyCase<State, Input> {
  input: Input;
  state: State;
}
```

#### `PropertyTestOptions` {#propertytestoptions}

Options for `propertyTest`: the optimistic `predict`, the eventual `apply`, the `cases`, and an optional `shape` projection.

**Signature**

```ts
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` {#propertytestresult}

The result of `propertyTest`: how many `cases` ran.

**Signature**

```ts
interface PropertyTestResult {
  cases: number;
}
```

## `@kovojs/test/csrf`

**Task:** Mutation-bound CSRF tokens for focused synthetic request tests.

Source: [`packages/test/src/csrf.ts`](https://github.com/kovojs/kovo/blob/main/packages/test/src/csrf.ts)

### Values

#### `mutationCsrfTokenForTesting` {#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` | <code>Request</code> | Synthetic request fixture used by the app's CSRF policy. |
| `options` | <code><a href="/api/server/#csrfoptions">CsrfOptions</a>&lt;Request&gt;</code> | The same CSRF options configured by the app. |
| `context` | <code>{ <a href="/api/server/#mutation">mutation</a>: string &#124; { readonly key: string } }</code> | Exact mutation handle or derived mutation key. |
| *(returns)* | <code>string</code> | A token accepted only for that mutation audience. |

**Signature**

```ts
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`](https://github.com/kovojs/kovo/blob/main/packages/test/src/headers.ts)

### Values

#### `headerValues` {#headervalues}

Read all values for header `name` from a `Headers` or {@link HeaderRecord}, case-insensitively (handles `set-cookie`).

**Signature**

```ts
function headerValues(source: Headers | HeaderRecord | undefined, name: string): string[];
```

#### `setCookieValues` {#setcookievalues}

Read all `set-cookie` header values from a `Headers` or {@link HeaderRecord}.

**Signature**

```ts
function setCookieValues(source: Headers | HeaderRecord | undefined): string[];
```

#### `cookiePair` {#cookiepair}

Return the `name=value` pair of a raw `set-cookie` string (drops attributes).

**Signature**

```ts
function cookiePair(setCookie: string | undefined): string;
```

#### `firstSetCookiePair` {#firstsetcookiepair}

Return the `name=value` pair of the first `set-cookie` on a `Headers` or {@link HeaderRecord}.

**Signature**

```ts
function firstSetCookiePair(source: Headers | HeaderRecord | undefined): string;
```

#### `decodeFrameworkIdentityToken` {#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**

```ts
function decodeFrameworkIdentityToken(value: unknown): string | undefined;
```

#### `enhancedMutationHeaders` {#enhancedmutationheaders}

Build the enhanced-mutation request headers used by app scenario tests (SPEC.md §9.1).

**Signature**

```ts
function enhancedMutationHeaders(
  options: EnhancedMutationHeaderOptions = {},
): Record<string, string>;
```

### Supporting types

#### `HeaderRecord` {#headerrecord}

A plain header bag accepted by the header helpers alongside a `Headers` instance.

**Signature**

```ts
type HeaderRecord = Record<string, string | string[] | undefined>;
```

#### `EnhancedMutationTarget` {#enhancedmutationtarget}

Structured mutation target selection for enhanced scenario requests.

**Signature**

```ts
interface EnhancedMutationTarget {
  queries?: readonly string[] | string;
  target: string;
}
```

#### `EnhancedMutationLiveTarget` {#enhancedmutationlivetarget}

Structured live-target descriptor for enhanced scenario requests.

**Signature**

```ts
interface EnhancedMutationLiveTarget {
  attestation: string;
  component: string;
  props?: Record<string, unknown>;
  target: string;
}
```

#### `EnhancedMutationHeaderOptions` {#enhancedmutationheaderoptions}

Options for {@link enhancedMutationHeaders}; targets follow the mutation wire protocol in SPEC.md §9.1.

**Signature**

```ts
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`](https://github.com/kovojs/kovo/blob/main/packages/test/src/harness.ts)

### Values

#### `createKovoTestHarness` {#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**

```ts
async function createKovoTestHarness<App extends KovoApp>(
  app: App,
  options: KovoTestHarnessOptions<App>,
): Promise<KovoTestContext<App>>;
```

### Supporting types

#### `PageAssertion` {#pageassertion}

Rendered page returned by {@link KovoTestContext.page}.

**Signature**

```ts
interface PageAssertion {
  /** Extract one named Kovo fragment from the full rendered response. */
  fragment(target: string): string;
  /** Full rendered response body. */
  html: string;
}
```

#### `DbVerificationDiagnostic` {#dbverificationdiagnostic}

Graph-honesty diagnostic observed while a harness executes database operations.

**Signature**

```ts
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` {#kovotestdb}

Database contract retained by the imported opaque app.

**Signature**

```ts
type KovoTestDb<App extends KovoApp> =
  InferKovoAppTypes<App> extends { readonly db: infer Db } ? Db : never;
```

#### `KovoTestRequest` {#kovotestrequest}

Request contract retained by the imported opaque app after provider inference.

**Signature**

```ts
type KovoTestRequest<App extends KovoApp> =
  InferKovoAppTypes<App> extends { readonly request: infer Request } ? Request : never;
```

#### `KovoTestRawRequest` {#kovotestrawrequest}

Raw request contract accepted by the imported app's custom-adapter boundary.

**Signature**

```ts
type KovoTestRawRequest<App extends KovoApp> =
  InferKovoAppTypes<App> extends { readonly rawRequest: infer Request }
    ? Request
    : globalThis.Request;
```

#### `KovoTestMutation` {#kovotestmutation}

Exact mutation-handle union assembled into the imported app.

**Signature**

```ts
type KovoTestMutation<App extends KovoApp> =
  InferKovoAppTypes<App> extends {
    readonly declarations: { readonly mutation: infer Mutation };
  }
    ? Mutation
    : never;
```

#### `KovoTestQuery` {#kovotestquery}

Exact query-handle union assembled into the imported app.

**Signature**

```ts
type KovoTestQuery<App extends KovoApp> =
  InferKovoAppTypes<App> extends {
    readonly declarations: { readonly query: infer Query };
  }
    ? Query
    : never;
```

#### `KovoTestRouteKey` {#kovotestroutekey}

Exact route-key union assembled into the imported app.

**Signature**

```ts
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` {#kovotestmutationinput}

Input inferred from one app-scoped mutation handle.

**Signature**

```ts
type KovoTestMutationInput<Mutation> =
  Mutation extends MutationHandle<infer Input, infer _Value, infer _Errors, infer _Owner>
    ? Input
    : never;
```

#### `KovoTestMutationValue` {#kovotestmutationvalue}

Successful value inferred from one app-scoped mutation handle.

**Signature**

```ts
type KovoTestMutationValue<Mutation> =
  Mutation extends MutationHandle<infer _Input, infer Value, infer _Errors, infer _Owner>
    ? Value
    : never;
```

#### `KovoTestMutationError` {#kovotestmutationerror}

Declared application-error union inferred from one app-scoped mutation handle.

**Signature**

```ts
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` {#kovotestframeworkmutationerror}

Framework-owned mutation failures that can precede an app handler.

**Signature**

```ts
type KovoTestFrameworkMutationError =
  | MutationFail<'CSRF', Record<never, never>>
  | MutationFail<'RATE_LIMITED', unknown>
  | MutationFail<'STALE_VERSION', Record<never, never>>
  | MutationFail<'UNAUTHORIZED', unknown>
  | MutationFail<'VALIDATION', ValidationFailurePayload>;
```

#### `KovoTestMutationResult` {#kovotestmutationresult}

Structured result inferred from one app-scoped mutation handle.

**Signature**

```ts
type KovoTestMutationResult<Mutation> =
  | KovoTestFrameworkMutationError
  | KovoTestMutationError<Mutation>
  | MutationSuccess<KovoTestMutationValue<Mutation>, KovoTestMutationInput<Mutation>>;
```

#### `KovoTestQueryInput` {#kovotestqueryinput}

Input inferred from one app-scoped query handle.

**Signature**

```ts
type KovoTestQueryInput<Query> =
  Query extends QueryHandle<infer Input, infer _Value, infer _Owner> ? Input : never;
```

#### `KovoTestQueryResult` {#kovotestqueryresult}

Result inferred from one app-scoped query handle.

**Signature**

```ts
type KovoTestQueryResult<Query> =
  Query extends QueryHandle<infer _Input, infer Value, infer _Owner> ? Awaited<Value> : never;
```

#### `KovoTestVerificationConfig` {#kovotestverificationconfig}

Runtime SQL-observation config; static graph facts always come from the verified artifact.

**Signature**

```ts
interface KovoTestVerificationConfig {
  domainByTable: Record<string, string>;
  exemptTables?: readonly string[];
  keyByTable?: Record<string, string>;
  sqlDialect?: 'postgres' | 'sqlite';
}
```

#### `KovoTestHarnessOptions` {#kovotestharnessoptions}

Explicit artifact and runtime fixtures for one imported app contract.

**Signature**

```ts
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` {#kovotestexecoptions}

Options for one direct app-scoped mutation execution.

**Signature**

```ts
interface KovoTestExecOptions<App extends KovoApp> {
  csrf?: CsrfOptions<KovoTestRequest<App>>;
  request?: Partial<Omit<KovoTestRequest<App>, 'db'>>;
}
```

#### `KovoTestContext` {#kovotestcontext}

App-scoped harness whose callable surface is inferred from one imported opaque app.

**Signature**

```ts
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`](https://github.com/kovojs/kovo/blob/main/packages/test/src/html-fragment.ts)

### Values

#### `fragmentHtml` {#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` | <code>string</code> | The full page or fragment-response HTML to search. |
| `target` | <code>string</code> | The fragment target name to resolve. |
| *(returns)* | <code>string</code> | The target's HTML, or `''` when no matching target exists. |

**Signature**

```ts
function fragmentHtml(html: string, target: string): string;
```

#### `htmlElementCount` {#htmlelementcount}

Counts the elements in `html` matching `selector`, a convenience over
{@link htmlElementFacts} for scenario assertions (SPEC.md §12).

| Parameter | Type | Description |
| --- | --- | --- |
| `html` | <code>string</code> | The HTML to scan. |
| `selector` | <code><a href="#htmlelementselector">HtmlElementSelector</a></code> | Tag/attribute filter; an empty selector matches every element. |
| *(returns)* | <code>number</code> | The number of matching elements. |

**Signature**

```ts
function htmlElementCount(html: string, selector: HtmlElementSelector = {}): number;
```

#### `htmlElementFacts` {#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` | <code>string</code> | The HTML to scan. |
| `selector` | <code><a href="#htmlelementselector">HtmlElementSelector</a></code> | Tag/attribute filter; an empty selector matches every element. |
| *(returns)* | <code><a href="#htmlelementfact">HtmlElementFact</a>[]</code> | Facts for every matching element, in document order. |

**Signature**

```ts
function htmlElementFacts(
  html: string,
  selector: HtmlElementSelector = {},
): HtmlElementFact[];
```

#### `htmlDocumentFacts` {#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` | <code>string</code> | The full page HTML. |
| *(returns)* | <code><a href="#htmldocumentfact">HtmlDocumentFact</a></code> | The aggregated {@link HtmlDocumentFact}. |

**Signature**

```ts
function htmlDocumentFacts(html: string): HtmlDocumentFact;
```

#### `htmlLinkHrefs` {#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` | <code>string</code> | The HTML to scan. |
| `attrs` | <code>Record&lt;string, string &#124; true&gt;</code> | Attribute filter applied to candidate `<link>` elements. |
| *(returns)* | <code>string[]</code> | The matching links' `href` values, in document order. |

**Signature**

```ts
function htmlLinkHrefs(html: string, attrs: Record<string, string | true> = {}): string[];
```

#### `kovoQueryJsonValues` {#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` | <code>string</code> | The page or fragment-response HTML. |
| `name` | <code>string</code> | The `<kovo-query>` name to read. |
| *(returns)* | <code>unknown[]</code> | The decoded JSON values for that name, or an empty array when absent. |

**Signature**

```ts
function kovoQueryJsonValues(html: string, name: string): unknown[];
```

#### `htmlFormFacts` {#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` | <code>string</code> | The page HTML to scan. |
| *(returns)* | <code><a href="#htmlformfact">HtmlFormFact</a>[]</code> | Facts for every form, in document order. |

**Signature**

```ts
function htmlFormFacts(html: string): HtmlFormFact[];
```

#### `htmlFormActions` {#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` | <code>string</code> | The page HTML to scan. |
| *(returns)* | <code>string[]</code> | Each form's `action`, in document order. |

**Signature**

```ts
function htmlFormActions(html: string): string[];
```

#### `htmlFormFields` {#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` | <code>string</code> | The page HTML to scan. |
| `name` | <code>string</code> | When provided, restricts results to fields with this `name`. |
| *(returns)* | <code><a href="#htmlformfieldfact">HtmlFormFieldFact</a>[]</code> | The matching field facts, in document order. |

**Signature**

```ts
function htmlFormFields(html: string, name?: string): HtmlFormFieldFact[];
```

#### `htmlFormFieldsByName` {#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` | <code><a href="#htmlformfact">HtmlFormFact</a> &#124; undefined</code> | The form fact whose fields to index, or undefined. |
| *(returns)* | <code>Record&lt;string, <a href="#htmlformfieldfact">HtmlFormFieldFact</a>&gt;</code> | A map from field name to {@link HtmlFormFieldFact}. |

**Signature**

```ts
function htmlFormFieldsByName(
  form: HtmlFormFact | undefined,
): Record<string, HtmlFormFieldFact>;
```

#### `htmlKeyFacts` {#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` | <code>string</code> | The page or fragment HTML to scan. |
| `key` | <code>string</code> | When provided, restricts results to elements with this `kovo-key`. |
| *(returns)* | <code><a href="#htmlkeyfact">HtmlKeyFact</a>[]</code> | The matching key facts, in document order. |

**Signature**

```ts
function htmlKeyFacts(html: string, key?: string): HtmlKeyFact[];
```

#### `htmlKeyValues` {#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` | <code>string</code> | The page or fragment HTML to scan. |
| *(returns)* | <code>string[]</code> | Each keyed element's `kovo-key`, in document order. |

**Signature**

```ts
function htmlKeyValues(html: string): string[];
```

#### `htmlKeyTextMap` {#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` | <code>string</code> | The page or fragment HTML to scan. |
| *(returns)* | <code>Record&lt;string, string&gt;</code> | A map from `kovo-key` to that element's text content. |

**Signature**

```ts
function htmlKeyTextMap(html: string): Record<string, string>;
```

#### `htmlTextContent` {#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` | <code>string</code> | The HTML fragment to reduce to text. |
| *(returns)* | <code>string</code> | The decoded, whitespace-collapsed text content. |

**Signature**

```ts
function htmlTextContent(html: string): string;
```

### Supporting types

#### `HtmlElementFact` {#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**

```ts
interface HtmlElementFact {
  attrs: Record<string, string>;
  html: string;
  innerHtml: string;
  tag: string;
}
```

#### `HtmlElementSelector` {#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**

```ts
interface HtmlElementSelector {
  attrs?: Record<string, string | true>;
  tag?: string;
}
```

#### `HtmlJsonScriptFact` {#htmljsonscriptfact}

One decoded JSON script found in a server-rendered document (SPEC.md §9.1, §12).

**Signature**

```ts
interface HtmlJsonScriptFact {
  attrs: Record<string, string>;
  html: string;
  json: unknown;
  rawJson: string;
}
```

#### `HtmlDocumentFact` {#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**

```ts
interface HtmlDocumentFact {
  bodyAttrs: Record<string, string>;
  jsonScripts: HtmlJsonScriptFact[];
  links: HtmlElementFact[];
  metas: HtmlElementFact[];
  text: string;
  title: string;
}
```

#### `HtmlFormFieldFact` {#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**

```ts
interface HtmlFormFieldFact {
  attrs: Record<string, string>;
  html: string;
  name: string;
  tag: string;
  type: string;
  value: string;
}
```

#### `HtmlFormFact` {#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**

```ts
interface HtmlFormFact {
  action: string;
  attrs: Record<string, string>;
  fields: HtmlFormFieldFact[];
  html: string;
  innerHtml: string;
  method: string;
}
```

#### `HtmlKeyFact` {#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**

```ts
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`](https://github.com/kovojs/kovo/blob/main/packages/test/src/pglite.ts)

### Values

#### `createPgliteTestDb` {#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` | <code>PGliteOptions</code> | PGlite options (e.g. data directory; defaults to in-memory). |
| *(returns)* | <code>Promise&lt;<a href="#pglitetestdb">PgliteTestDb</a>&gt;</code> | A ready `PgliteTestDb`. |

**Signature**

```ts
async function createPgliteTestDb(options: PGliteOptions = {}): Promise<PgliteTestDb>;
```

### Supporting types

#### `PgliteStatementCarrier` {#pglitestatementcarrier}

SQL statement object accepted by `PgliteTestDb` helpers.

**Signature**

```ts
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` {#pglitestatementinput}

SQL statement input accepted by `PgliteTestDb` helpers.

**Signature**

```ts
type PgliteStatementInput = string | PgliteStatementCarrier;
```

#### `PgliteTestDb` {#pglitetestdb}

A PGlite-backed test database handle: `exec`/`query` SQL helpers plus `read`/`write` and `close`.

**Signature**

```ts
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`](https://github.com/kovojs/kovo/blob/main/packages/test/src/postgres.ts)

### Values

#### `createPostgresTestRuntime` {#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**

```ts
async function createPostgresTestRuntime(
  options: KovoPostgresTestRuntimeOptions,
): Promise<KovoPostgresTestRuntime>;
```

### Supporting types

#### `KovoPostgresTestDb` {#kovopostgrestestdb}

Drizzle database handle passed to owner-scoped Postgres test callbacks.

**Signature**

```ts
type KovoPostgresTestDb = KovoPostgresRuntimeDb;
```

#### `KovoPostgresTestAdminDb` {#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**

```ts
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` {#kovopostgrestestsystemdb}

Drizzle database handle passed to audited non-request system test callbacks.

**Signature**

```ts
type KovoPostgresTestSystemDb = KovoPostgresRuntimeDb;
```

#### `KovoPostgresTestRuntimeOptions` {#kovopostgrestestruntimeoptions}

Configuration for an ephemeral owner-scoped Postgres test runtime.

**Signature**

```ts
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` {#kovopostgrestestruntime}

Ephemeral PGlite-backed runtime that exercises Kovo's real Postgres RLS posture.

**Signature**

```ts
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`](https://github.com/kovojs/kovo/blob/main/packages/test/src/sqlite.ts)

### Values

#### `createSqliteTestDb` {#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` | <code><a href="#sqlitetestdboptions">SqliteTestDbOptions</a></code> | better-sqlite3 options. |
| *(returns)* | <code><a href="#sqlitetestdb">SqliteTestDb</a></code> | A ready `SqliteTestDb`. |

**Signature**

```ts
function createSqliteTestDb(options: SqliteTestDbOptions = {}): SqliteTestDb;
```

### Supporting types

#### `SqliteStatementCarrier` {#sqlitestatementcarrier}

SQL statement object accepted by `SqliteTestDb` helpers.

**Signature**

```ts
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` {#sqlitestatementinput}

SQL statement input accepted by `SqliteTestDb` helpers.

**Signature**

```ts
type SqliteStatementInput = string | SqliteStatementCarrier;
```

#### `SqliteNativeStatement` {#sqlitenativestatement}

Minimal better-sqlite3 statement handle surfaced by `SqliteTestDb.sqlite`.

**Signature**

```ts
interface SqliteNativeStatement<Row = unknown> {
  all(...params: unknown[]): Row[];
  run(...params: unknown[]): unknown;
}
```

#### `SqliteNativeHandle` {#sqlitenativehandle}

Minimal better-sqlite3 database handle surfaced by `SqliteTestDb.sqlite`.

**Signature**

```ts
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` {#sqlitetestdboptions}

Options passed through to the better-sqlite3 constructor used by `createSqliteTestDb()`.

**Signature**

```ts
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` {#sqlitetestdb}

A better-sqlite3-backed test database handle: raw SQLite plus SQL and row helpers.

**Signature**

```ts
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;
}
```

