Skip to content

hamur/test

Builds your app and serves it inside bun test, so a test calls its pages and routes as a client does. It is part of hamur and adds no dependency. Nothing of it reaches a build: a test build is a normal production build of your app whose .hamur/ and .output/ sit in a temp dir.

ts
// test/app.test.ts
import { $fetch, fetch, setup } from "hamur/test"
import { expect, test } from "bun:test"

setup({ rootDir: import.meta.dir + "/.." })

test("the home page answers", async () => {
  expect((await fetch("/")).status).toBe(200)
  expect(await $fetch("/api/greet")).toEqual({ hello: "world" })
})

Every error of hamur/test starts hamur/test: ; an error of the app or of its build passes through as it is.

setup

ts
function setup(options?: SetupOptions): void

Call it once, at the top level of a test file. It checks its options at once, so a bad option fails the file before any build, then registers one beforeAll and one afterAll (from bun:test, or from Vitest's globals, see Vitest) and records the file's test app.

The beforeAll (timeout setupTimeout) builds the app in place: rootDir is built as hamur build builds it, so its own node_modules, layers and workspace links resolve as usual, but buildDir and outputDir point into a new temp dir node_modules/.cache/hamur-test-<name>-* below rootDir (so the modules the build generates resolve your packages) and no source file of rootDir is written. NODE_ENV stays test, as bun test sets it, so the config's $test block applies. Then it serves the build:

serverWhat runsWhere fetch goes
"in-process" (default under bun test)the built .output/server/index.mjs, imported into the test process; its fetch export, else default.fetch. The static preset and the other prerendering presets are served from the public output as hamur preview serves themthe handler, without a socket. A port opens only with browser: true or port, through the entry's listen
"bun" (default under Vitest), "node".output/server/index.mjs in a bun or node process, listening on a free port of 127.0.0.1 through the entry's listen, with env and the dotenv values; the test process's own process.env is put back after the buildhttp://127.0.0.1:<port>
dev: truehamur dev in a child process on a free port, its buildDir in the temp dirthe dev server

A server process counts as started once it printed the origin it bound (hamur dev its Local: line) and HEAD / there answers with any status, so a port another process holds is never taken for the app. A process that exits first, or a start that has not finished within setupTimeout (the build included), fails the beforeAll with the process's output.

The afterAll stops everything, also after a failed or timed-out beforeAll, and an interrupted run (Ctrl-C) stops the server processes and removes the temp dir as well: it closes the listener, sends each child process SIGTERM (SIGKILL after 5 s) and waits for it to exit, removes the temp dir and puts back each variable env set. After the file the port is free, no child process is left and the temp dir is gone.

Errors when the options are checked:

  • hamur/test: setup was called twice in this file; use buildModuleFixture for a second app
  • hamur/test: server must be "in-process", "bun" or "node" (got "deno")
  • hamur/test: dev: true runs hamur dev in a child process; leave server unset
  • hamur/test: setup builds into a temp dir; remove overrides.buildDir (or overrides.outputDir)
  • hamur/test: overrides must be JSON for a build in another process; overrides.hooks["build:done"] is a function (with dev: true)
  • hamur/test: overrides must be JSON for a build in another process; overrides.modules[0] is a module no file exports; export it from a file of its own for a build in another process (with dev: true)
  • hamur/test: dotenv must be true, false or a file path (got 1)

Errors of the beforeAll:

  • hamur/test: server "node" runs .output/server/index.mjs with node; build it with preset "node" (got "bun")
  • hamur/test: preset "static" builds no server; use server "in-process"
  • hamur/test: preset "vercel" builds no fetch handler hamur/test can call; use preset "bun" or "node"
  • hamur/test: bun .output/server/index.mjs exited with 1: and the output
  • hamur/test: the test app did not answer on http://127.0.0.1:<port> within 120000 ms: and the output

SetupOptions

KeyTypeDefault
rootDirstringprocess.cwd()
presetstring"bun" (overrides.preset when only that is set); with dev: true the app's own
server"in-process" | "bun" | "node""in-process", "bun" under Vitest; "node" needs a build with preset "node", "bun" runs a bun or node build
devbooleanfalse; true takes no server
browserbooleanfalse; true opens a port in process, so url() works
portnumbera free port, only when one is opened
envRecord<string, string>{}: set over process.env for the build and, in process, for the file; a child process gets them as its environment
overridesHamurConfig{}: merged over hamur.config.ts as the config's own blocks are; JSON for a build in another process, except modules, whose imported modules go by their file and export
modestring"production", "development" with dev: true; another value reads .env.<mode> as --mode does
dotenvboolean | stringtrue: the test files (.env, .env.test, .env.test.local) of rootDir over the values Bun took from the cwd's files and never over a shell value; when rootDir is the cwd Bun already read them. false: every value Bun took from the cwd's files is removed. A path is read after them as --dotenv reads it. mode adds .env.<mode>, and env is set last
storage"app" | "memory""app"; "memory" gives every storage mount of the resolved config, the modules' and the default data mount included, the memory driver for the test build, in a child process too; devStorage overlays go
runner"bun" | "vitest""vitest" when process.env.VITEST is set, else "bun"
setupTimeoutnumber120000 ms, for the build and the start together

Vitest

hamur/test never imports vitest. When process.env.VITEST is set, or with runner: "vitest", setup takes beforeAll and afterAll from the global scope, so the Vitest config needs globals: true:

ts
export default { test: { globals: true } }

Under Vitest the build runs in a bun child process (bun must be on PATH), server defaults to "bun" and "node" is allowed, createPage uses the "cdp" backend, and mockEvent and callHandler run on Node. overrides must be JSON, as with dev: true. The source and browser places (renderPage, renderComponent, mountSuspended, mockComponent, registerEndpoint) and useFakeTime need bun test and throw hamur/test: <name> needs bun test.

  • hamur/test: setup under vitest needs globals: true in the vitest config
  • hamur/test: server "in-process" needs bun test; use "node" or "bun"

useTestContext, TestApp

ts
function useTestContext(): TestApp

interface TestApp {
  readonly rootDir: string
  readonly outputDir: string
  readonly server: "in-process" | "bun" | "node" | "dev"
  url(path?: string): string
  fetch(path: string, init?: RequestInit): Promise<Response>
  $fetch: $Fetch<HamurFetchRoutes>
  html(path: string, init?: RequestInit): Promise<string>
  json<T = unknown>(path: string, init?: RequestInit): Promise<T>
  getServerLogs(): string
  close(): Promise<void>
}

Every helper puts a path from the root below the app's app.baseURL, in process and out of process alike: with app.baseURL: "/sub/", fetch("/api/x") and fetch("/sub/api/x") both request /sub/api/x. An absolute URL is fetched as it is.

The file's test app, once setup ran; without it hamur/test: useTestContext() found no test app; call setup() at the top of this file. rootDir is absolute and outputDir is <temp>/.output. Each method is also exported on its own and does the same. A method called before the beforeAll finished, at a file's top level, throws hamur/test: fetch ran before setup finished; call it inside a test or a hook, naming itself. close() is the teardown of the afterAll.

fetch

ts
function fetch(path: string, init?: RequestInit): Promise<Response>

A request to the test app. In process the path, below app.baseURL, is resolved against http://localhost and handed to the handler; otherwise it is resolved against the server's origin. An absolute URL is fetched as it is. Assert a status with fetch.

$fetch

ts
const $fetch: $Fetch<HamurFetchRoutes>

The app's own $fetch client bound to the test app: in process it calls the handler with no socket, otherwise it sends to the server's origin; either way it joins app.baseURL unless the call passes its own baseURL. When hamur typegen ran in the app, HamurFetchRoutes types each route's result. Like the app's $fetch it throws a FetchError on a status of 400 or more.

html, json

ts
function html(path: string, init?: RequestInit): Promise<string>
function json<T = unknown>(path: string, init?: RequestInit): Promise<T>

html sends accept: text/html unless init sets accept, and reads the body as text; json reads it as JSON. Neither checks the status.

url

ts
function url(path?: string): string

The absolute URL of path (default /) below app.baseURL, http://127.0.0.1:<port>/sub/x for url("/x") with app.baseURL: "/sub/". It needs a port: with server: "in-process", browser: true or port; without one hamur/test: url() needs a port; call setup({ browser: true }) or use server "bun" or "node".

getServerLogs

ts
function getServerLogs(): string

What the server process ("bun", "node" or hamur dev) wrote to stdout and stderr so far. In process the app logs to the test process's own output, so it throws hamur/test: getServerLogs() reads a server process; with server "in-process" the server logs to this process.

mockEvent, MockEventOptions

ts
function mockEvent(input: string | Request, options?: MockEventOptions): HamurEvent

interface MockEventOptions {
  method?: string
  headers?: HeadersInit
  body?: BodyInit | Record<string, unknown> | unknown[]
  params?: Record<string, string | string[]>
  context?: Record<string, unknown>
  runtimeConfig?: Record<string, unknown>
}

A real HamurEvent, built as the server builds one, for a handler the test imported itself. A string input is a path ("/api/x?a=1") made into new Request("http://localhost/api/x?a=1", …), so getQuery(event).a is "1". method is "GET", or "POST" when body is set. An object or array body is sent as JSON with content-type: application/json unless headers sets one. params is what getRouterParam(event, "id") reads, context is assigned onto event.context, and runtimeConfig is merged over { public: {} }.

  • hamur/test: mockEvent needs a path such as "/api/x" or a Request (got "api/x")
  • hamur/test: mockEvent cannot send a body with GET

callHandler

ts
function callHandler(
  handler: Handler<any, any> | ((event: HamurEvent) => unknown),
  event: HamurEvent,
): Promise<Response>

Answers event as the server answers one request, without a server or a build. handler is a defineHandler result or a function of the event.

ts
import { callHandler, mockEvent } from "hamur/test"
import { greet } from "../server/api/greet.ts"

const response = await callHandler(greet, mockEvent("/api/greet?name=Ada"))
expect(await response.json()).toEqual({ hello: "Ada" })

A defineHandler result reads its input as its route does (path parameters, query, JSON body), or, without a route, as <baseURL>_hamur/fn/<id> does; its input schema answers 400 with the issues, and it runs with its own middleware. A thrown HTTP error (createError, fail() as its status) answers as the server answers it; any other throw answers the masked 500 of production and is not rethrown. To see the thrown error itself, call the handler as a function: await greet(input, { event }).

useStorage inside the call reads one set of memory mounts per test file, shared by every call in the file, so a POST then a GET see the same data: a mount for each name of the app's storage (when setup built it in this process) and for data. The set is dropped when the file's setup closes.

  • hamur/test: callHandler needs a handler of defineHandler or a function of the event (got object)
  • hamur/test: callHandler cannot call the websocket handler /ws; test it against setup with a WebSocket

createPage, CreatePageOptions

ts
function createPage(path?: string, options?: CreatePageOptions): Promise<TestPage>

interface CreatePageOptions {
  width?: number // 1280
  height?: number // 720
  backend?: "chrome" | "webkit" | "cdp"
  wait?: "hydration" | "load" // "hydration"
}

Opens a page of a real browser, no driver package needed. A path from the root opens the test app and needs a port: setup({ browser: true }), or server: "bun", "node" or dev: true. An absolute URL opens any server, and without path the page is about:blank. The pages still open when the file ends are closed by the afterAll of setup, with the browser.

ts
import { createPage, hasBrowser, setup } from "hamur/test"
import { expect, test } from "bun:test"

setup({ rootDir: import.meta.dir + "/..", browser: true })

test.skipIf(!hasBrowser())("the about link navigates on the client", async () => {
  const page = await createPage("/")
  await page.click("a[href='/about']")
  await page.waitFor("h1")
  expect(page.requests.filter((request) => request.type === "Document")).toHaveLength(1)
  expect(page.problems()).toEqual([])
  await page.close()
})
backendWhat drives the page
unset"chrome" under bun test; "cdp" under Node (Vitest) or in a Worker, and when Bun.WebView cannot start (one line [hamur/test] Bun.WebView could not start (…); using the CDP client)
"chrome"Bun.WebView on a fresh headless Chrome. Every page shares one profile, so createPage clears the cookies and storage of the origin before its first visit; two pages that must hold different cookies at once need "cdp"
"webkit"Bun.WebView on the system WebKit, macOS only. It has no DevTools events: requests throws and consoleMessages has no uncaught exceptions
"cdp"Hamur's own DevTools client on headless Chrome, which runs under Node too; each page is a browser context of its own

Chrome is looked up in BUN_CHROME_PATH, CHROME_PATH, google-chrome, google-chrome-stable, chromium and chromium-browser on PATH, then the macOS app bundles of Chrome and Chromium.

  • hamur/test: no browser found; set BUN_CHROME_PATH or install Chrome
  • hamur/test: backend must be "chrome", "webkit" or "cdp" (got "firefox")
  • hamur/test: backend "webkit" runs on macOS only
  • hamur/test: createPage("/") needs a test app with a port; call setup({ browser: true }) or pass an absolute URL

TestPage

ts
interface TestPage {
  readonly url: string
  readonly consoleMessages: ReadonlyArray<{ type: string; text: string }>
  readonly requests: ReadonlyArray<{ url: string; type: string }>
  goto(path: string, options?: { wait?: "hydration" | "load" }): Promise<void>
  back(): Promise<void>
  forward(): Promise<void>
  reload(): Promise<void>
  click(selector: string, options?: { timeout?: number }): Promise<void>
  type(selector: string, text: string): Promise<void>
  press(key: string, options?: { modifiers?: ("Shift" | "Control" | "Alt" | "Meta")[] }): Promise<void>
  evaluate<T = unknown>(script: string | (() => T | Promise<T>)): Promise<T>
  waitFor(selector: string, options?: { timeout?: number }): Promise<void>
  text(selector?: string): Promise<string>
  html(selector?: string): Promise<string>
  problems(allow?: (message: { type: string; text: string }) => boolean): string[]
  screenshot(options?: { format?: "png" | "jpeg" | "webp"; quality?: number }): Promise<Blob>
  close(): Promise<void>
}

goto (and back, forward, reload) waits for the load event of the page, then, with wait: "hydration", until the client stamped history.state before it hydrated, then two animation frames; a page without a module script is ready at its load event. It waits 10 s at most. A path from the root goes below the test app's app.baseURL; on a page opened at an absolute URL it is resolved against that URL.

  • click and waitFor wait for the selector (10 s by default); click sends real mouse events at the element's centre.
  • type clicks the element, then inserts text as a paste does: no keydown fires. Test key handling with press, which takes a single character or Enter, Tab, Space, Backspace, Delete, Escape, the arrows, Home, End, PageUp and PageDown.
  • evaluate takes an expression, or a function sent as its source (it has no closure), and returns its value, awaited and copied as JSON.
  • text reads the trimmed lines of the app root (#<app.rootId>) or of the first element of selector; html the whole document or that element's outerHTML.
  • consoleMessages holds every console.* call, uncaught exception and browser log entry, type one of log, info, warn, error, debug, exception; problems lists the error, warn and exception ones as [type] text, less those allow matches.
  • requests lists every request of the page; type is Chrome's resource type, Document for a document.
  • screenshot returns the viewport as a Blob, PNG by default; webp needs Chrome.

Errors:

  • hamur/test: /about did not hydrate within 10000 ms (readyState "complete", history.state has no hamurKey)
  • hamur/test: waitFor("#x") found no element within 10000 ms (click, type, text and html the same, with their name)
  • hamur/test: evaluate(document.querySelector("x").click()) threw: TypeError: …, the script cut at 80 characters
  • hamur/test: page.requests needs backend "chrome" or "cdp"
  • hamur/test: the page is closed

hasBrowser

ts
function hasBrowser(backend?: "chrome" | "webkit" | "cdp"): boolean

Whether createPage finds a browser for backend, without starting one: the Chrome lookup above, or macOS for "webkit". A file skips its browser tests with test.skipIf(!hasBrowser())(…).

renderPage, RenderPageTestOptions, RenderedTestPage

ts
function renderPage(path: string, options?: RenderPageTestOptions): Promise<RenderedTestPage>

interface RenderPageTestOptions {
  data?: unknown
  state?: Record<string, unknown>
  runtimeConfig?: Record<string, unknown>
  headers?: HeadersInit
}

interface RenderedTestPage {
  status: number
  headers: Headers
  html: string
  head: string
  payload: unknown
  redirect?: string
  error?: unknown
}

Renders one page of the app in the test process, from its source, with no setup and no build: the app's files are loaded through the test preload's plugin (below) and the page goes through the server entry's renderPage, so route middleware, loaders, access rules and server hooks run, while defineServer middleware and routeRules() do not. path is below app.baseURL, as for fetch. An unknown path answers the app's not-found page with status 404.

ts
import { renderPage } from "hamur/test"
import { expect, test } from "bun:test"

test("the post shows its loader data", async () => {
  const page = await renderPage("/blog/x", { data: { post: "mocked" } })
  expect(page.status).toBe(200)
  expect(page.html).toContain("Post: mocked")
})
  • data is what the matched page's load returns; that load does not run, the loaders of its parent pages and layouts do.
  • state sets useState values before the app's plugins run; runtimeConfig is merged key by key over the app's for every request of the render: useRuntimeConfig() in components, a loader's ctx.runtimeConfig, and useRuntimeConfig(event) in the server routes it fetches in process.
  • headers are the request's headers (cookie, accept-language, …).
  • html is the whole document, head the text between <head> and </head>, payload the page payload. A redirect answer gives its Location in redirect and an empty html.
  • error is the value the render threw, as thrown: expect(page.error).toBe(thrown). See "A render that threw" below.

The overrides belong to the one call, so concurrent tests do not see each other's.

renderComponent, RenderComponentOptions, RenderedComponent

ts
function renderComponent(component: unknown, options?: RenderComponentOptions): Promise<RenderedComponent>

interface RenderComponentOptions {
  props?: Record<string, unknown>
  route?: string
  params?: Record<string, string | string[]>
  state?: Record<string, unknown>
  runtimeConfig?: Record<string, unknown>
}

interface RenderedComponent {
  status: number
  html: string
  head: string
  error?: unknown
}

Renders one component through the adapter's own server render, as the only page of a route table whose path is route (default "/"), with no layout and no app root, inside the app context: the app's plugins, app and runtime config, head and state. It resolves once the component's async data settled, and its useFetch("/api/x") reaches the app's server routes. html is the inner HTML of #<app.rootId>; status is 200, or the status of the error page the render ended in.

ts
const { html } = await renderComponent("app/components/Greeting.vue", { props: { name: "Ada" }, route: "/x" })
  • component is a module path relative to the app root, which the test preload's plugin compiles for every library, a component value the test imported itself (what the library renders; an html component is a function returning a string), or a RouteStub of createRouteStub, which replaces the app's route table for the render and shows its route at route, by default the stub's initialURL; props does not apply to a stub.
  • route sets the path, query and hash useRoute() reads; each of params names the segments of route that hold its value ({ route: "/posts/1", params: { id: "1" } }), and a value that is no segment of route throws.

A render that threw

An error thrown while rendering (a loader, a layout, the component) is answered as in a request: the app's error page in html, with the error's status (500 for a ReferenceError, 403 for createError({ status: 403 })). status and html are the same for a test of an error page. The result also holds error, the value that was thrown, not the HamurError that wraps it for the page: (result.error as Error).message, expect(result.error).toBe(thrown). error is absent from the result, not undefined, when nothing was caught: a page that rendered, a redirect, a not-found page nothing threw. An error the app masks while the render succeeds (a failed useAsyncData, an error boundary of the library) is not error; the status is 200.

The app's logger writes a caught render error once, at error, to the test process's stderr (a JSON line, HAMUR_LOG_LEVEL and HAMUR_LOG_FORMAT apply), as for a request; hamur/test writes no second line. An error the app answers below 500 (createError({ status: 403 })) is logged at debug.

Errors of renderPage and renderComponent

  • hamur/test: renderPage needs bun test (renderComponent the same): under Vitest or outside Bun
  • hamur/test: renderPage renders on the server; unset HAMUR_TEST_TARGET or set it to "server"
  • hamur/test: renderPage data replaces the loader of a page; /about has no load
  • hamur/test: renderComponent component must be a module path, a component or a route stub (got number)
  • hamur/test: renderComponent "app/components/X.vue" does not resolve from <rootDir>
  • hamur/test: renderComponent route must be a path starting with "/" (got "x")
  • hamur/test: renderComponent params.id is not a segment of route "/posts/1"
  • hamur/test: HAMUR_TEST_TARGET must be "server" or "client" (got "browser")
  • hamur/test: the test preload serves /a; run the tests of /b in their own bun test run

registerEndpoint, EndpointHandler

ts
type EndpointHandler = (event: HamurEvent) => unknown
function registerEndpoint(
  path: string,
  handler: EndpointHandler | { method?: string; handler: EndpointHandler; once?: boolean },
): () => void

Answers a request for path before the app's own routes: the request-bound fetch (useFetch, $fetch, a loader's ctx.fetch) inside renderPage and renderComponent, and every request a page of mountSuspended makes to its mount server. A request that matches no registration reaches the app's routes, in renderComponent as in renderPage.

ts
registerEndpoint("/api/users/:id", (event) => ({ id: event.params.id, name: "Ada" }))
const { html } = await renderComponent("app/components/UserCard.vue")
  • path is a route pattern (/api/users/:id binds event.params.id), matched against the path without the query. method defaults to "*"; GET also answers HEAD.
  • The handler gets the request's HamurEvent, and its return value is answered as a server handler's is: an object as JSON, a string as text, a Response as it is.
  • The last registration of a path and method wins. once: true answers one request and then lets the earlier registration or the app answer.
  • The function it returns removes that registration. The first call registers an afterAll that removes the rest, so a registration ends with its file; called first inside a test body, where Bun refuses a hook, it ends with its remover.
  • It never reaches setup's test app, which is a built bundle.
  • hamur/test: registerEndpoint needs bun test: under Vitest or outside Bun.
  • hamur/test: registerEndpoint needs a route pattern such as "/api/x" (got "api/x")

useFakeTime, FakeTime

ts
function useFakeTime(start?: Date | number): FakeTime

interface FakeTime {
  readonly now: number
  advance(ms: number): void
  set(time: Date | number): void
  restore(): void
}

Moves this process's clock with setSystemTime of bun:test, from start or the present, so Date.now(), new Date() and Intl read the fake clock. advance(ms) moves it forward, set to a time, restore() calls setSystemTime(). Timers are not faked (jest.useFakeTimers of bun:test does that).

ts
const clock = useFakeTime()
await $fetch("/api/report")
clock.advance(61_000)
await $fetch("/api/report")
clock.restore()
  • It reaches mockEvent, callHandler, renderPage, renderComponent and setup's server: "in-process": a GET handler with cache: { maxAge: 60, swr: true } answers stale after advance(61_000), with no real wait.
  • The first call registers an afterAll that restores an active clock; called first inside a test body, where Bun refuses a hook, the clock lasts until restore().
  • hamur/test: useFakeTime moves the clock of this process; the test app runs in a "bun" process, use server "in-process"
  • hamur/test: useFakeTime is already active; call restore() first
  • hamur/test: advance needs milliseconds of 0 or more (got -1)
  • hamur/test: useFakeTime needs bun test

createRouteStub, RouteStub, RouteStubRecord

ts
interface RouteStubRecord {
  path: string
  component: unknown
  load?: (ctx: LoadContext) => unknown
  children?: RouteStubRecord[]
}

function createRouteStub(routes: RouteStubRecord[], options?: { initialURL?: string }): RouteStub

A route table and a start URL, nothing else. renderComponent and mountSuspended accept it as component and replace the app's table with it for that render or mount. path is the route's full path (a child's path holds its parent's), component a module path relative to the app root or a component value, load the route's loader. initialURL is "/" by default.

ts
const stub = createRouteStub([
  { path: "/", component: "app/pages/index.tsx", load: () => ({ n: 1 }) },
  { path: "/about", component: "app/pages/about.tsx" },
])
const { html } = await renderComponent(stub)
  • Its loaders run in the test process: on the server render, and in mountSuspended for each navigation, which the page sends to the mount server as a payload request. The browser side runs on a memory history at initialURL, so a Link between two stubbed routes changes the shown route with no document request.
  • In mountSuspended every component must be a module path.
  • hamur/test: createRouteStub route path must start with "/" (got "a")
  • hamur/test: createRouteStub has the path "/a" twice
  • hamur/test: createRouteStub route "/a" needs a component
  • hamur/test: createRouteStub initialURL "/c" matches no route

createAuthorizer, Authorizer, AuthorizerOptions, AuthorizerRequest, AuthorizerResult, AuthorizerEntity

ts
function createAuthorizer(options?: { rootDir?: string }): Promise<Authorizer>

interface Authorizer {
  check<A extends ActionName>(request: {
    principal: EntityRef<PrincipalOf<A>>
    action: A
    resource: EntityRef<ResourceOf<A>>
    context?: ContextOf<A>
    entities: AuthorizerEntity[]
    links?: Array<{ template: string; principal?: EntityRef; resource?: EntityRef }>
  }): AuthorizerResult
}

interface AuthorizerResult {
  decision: "allow" | "deny"
  determining: string[]
  errors: Array<{ policy: string; message: string }>
}

Tests the policies of server/policies/ without a server or an entity source. createAuthorizer reads, validates and compiles the policies of rootDir (default process.cwd()) and of its layers with the build's own code. check evaluates one request against the entities the test gives, in Cedar's JSON entity form (uid, attrs, parents, tags), typed by HamurAuthz; an attribute is written as an entity source returns it. determining lists the ids of the policies that decided; an entity a policy needs and the test did not give is missing, so that policy errs and is listed in errors. links are the template links of the request, as links of defineEntities returns them.

Errors:

  • a policy or schema error of the build throws its message prefixed hamur/test:
  • hamur/test: check.action "mov" is not an action of the authorization schema (did you mean "move"?)
  • hamur/test: action "move" does not apply to a principal of type "Clerk" and a resource of type "Warehouse"
  • hamur/test: entity Clerk::"ada" has attribute "name" = 1; the schema declares String
  • hamur/test: template link names "doc-owner", which is not a template
  • hamur/test: check.links is [object Promise], which is not a list of template links

It runs under Vitest too: there the policies are read in a bun child process.

buildModuleFixture

ts
function buildModuleFixture(
  rootDir: string,
  options?: Omit<SetupOptions, "rootDir" | "runner" | "setupTimeout"> & { framework?: string },
): Promise<TestApp>

For a module's own tests: a directory of the module, packages/<module>/test/fixtures/<name>/, built and served as setup does it (in place, into a temp dir, with the same server, env, dotenv and storage options) but with no hooks, so one file can build several apps. It resolves with the test app; the test calls close(), in a finally or an afterAll. framework is the same as overrides.framework, and overrides is where a module test adds the module under test to modules or a page through an extra dir.pages folder. A failed start closes everything it made before it throws. The fetch, html and json functions of hamur/test do not use this app; call its own methods.

  • hamur/test: buildModuleFixture rootDir <rootDir> does not exist
  • every error of setup's options, at the call

forEachAdapter, Library

ts
type Library = "react" | "vue" | "preact" | "svelte" | "solid" | "html"

function forEachAdapter(
  rootDir: string,
  body: (library: Library, app: () => TestApp) => void,
  options?: Omit<SetupOptions, "rootDir" | "runner"> & { framework?: string },
): void

Reads the directories of rootDir named after the six libraries. For each one present it registers describe("<library>") with a beforeAll that builds <rootDir>/<library> as buildModuleFixture does (with options, and setupTimeout for the build) and an afterAll that closes it, and calls body inside, so the tests body registers carry the library in their names. app() is that library's test app and works inside a test or a hook. It works under bun test and under Vitest with globals: true, as setup does.

ts
forEachAdapter(
  import.meta.dir + "/fixtures",
  (library, app) => {
    test(`/ renders in ${library}`, async () => expect(await app().html("/")).toContain("hello"))
  },
  { overrides: { modules: [module] } },
)
  • hamur/test: forEachAdapter found no library directory in <rootDir>; expected react, vue, preact, svelte, solid or html
  • every error of setup's options, at the call
  • under Vitest without globals: hamur/test: forEachAdapter under vitest needs globals: true in the vitest config

hamur/test/preload

The test preload, for bunfig.toml's [test] preload, which loads the app's own files in the test process with the build's transforms:

toml
# bunfig.toml
[test]
preload = ["hamur/test/preload"]

Its plugin loads the app of HAMUR_TEST_ROOT (default: the working directory) for HAMUR_TEST_TARGET (server, the default, or client): the build's virtual modules, aliases, asset URLs, transform chain and the adapter's compile plugin (.vue, .svelte, Solid's .tsx), for the files of the app's source dirs and of its adapter, never node_modules, a *.test.* file or a built .output/. A test file is not transformed: it imports what it uses, such as import Counter from "./app/components/Counter.vue", as every app file does. One process serves one app. renderPage and renderComponent register the plugin on their first call, so a component given as a module path needs no bunfig.toml; a component the test file imports needs the preload when it has a compile step.

  • hamur/test: HAMUR_TEST_TARGET must be "server" or "client" (got "browser")
  • an import of a #hamur/ module the build does not know, from a file of the app, fails with Unknown virtual module "#hamur/x". Known: …

hamur/test/internal

For @hamur/test-utils only, not for apps, like hamur/server/internal. It makes no promise across minor releases. It exports mountServer, the in-process server mountSuspended mounts its components from, isRouteStub and firstValue, which mountSuspended reads a route stub with, useTestLoader and TestLoader, the test preload's plugin and its build context, which @hamur/mail/test reads the build dir from, mockComponentFile and componentMocks, which every mockComponent of @hamur/test-utils calls and mountSuspended reads, and PropsOf<C, Props>, which each entry of @hamur/test-utils fills with its library's prop type.