Testing
hamur/test builds your app and calls it from bun test. @hamur/test-utils adds the component helpers of your UI library. Both are for tests only: nothing of them reaches a build, and neither adds a dependency (hamur/test is part of hamur; @hamur/test-utils names hamur, the adapter and the library as peers). The reference is hamur/test and @hamur/test-utils; this page is the guide.
hamur init writes test/app.test.ts and the script "test": "bun test", so a new app runs bun test at once: the test builds the app, serves it and checks that / answers 200. Every sample on this page is a test file of a small app in the Hamur repository, and the repository runs it on every change.
A test runs your app in one of three places, and each helper names its place.
| Place | How the app is loaded | Helpers |
|---|---|---|
| Built | setup builds the app into a temp dir and serves .output/ | setup, fetch, $fetch, html, json, url, useTestContext, getServerLogs, createPage |
| Source | the test preload loads your files in the test process with the build's transforms; mocks apply | renderPage, renderComponent, renderSuspended, mockComponent, registerEndpoint, createRouteStub |
| Browser | mountSuspended builds a client bundle of one component and opens it in Chrome | mountSuspended |
mockEvent and callHandler run a handler you imported yourself, with no build, on any runner.
Install
hamur/test needs nothing. The component helpers of your library come from @hamur/test-utils, which has one entry for each of react, vue, preact, svelte and solid. html has no client components, so it has no entry.
bun add -d @hamur/test-utils
Unit tests of server code
mockEvent makes a real HamurEvent the way the server makes one, and callHandler answers it the way the server answers a request, without a server or a build.
import { callHandler, mockEvent } from "hamur/test"
import { expect, test } from "bun:test"
import { addNote, getGreet, getNote, listNotes } from "../server/index.ts"
test("a handler greets the name in the query", async () => {
const response = await callHandler(getGreet, mockEvent("/api/greet?name=Ada"))
expect(response.status).toBe(200)
expect(await response.json()).toMatchObject({ hello: "Ada" })
})
test("a note added by one call is read by the next", async () => {
const added = await callHandler(addNote, mockEvent("/api/notes", { body: { text: "buy milk" } }))
const { id } = (await added.json()) as { id: string }
const note = await callHandler(getNote, mockEvent(`/api/notes/${id}`, { params: { id } }))
expect(await note.json()).toEqual({ text: "buy milk" })
const listed = await callHandler(listNotes, mockEvent("/api/notes"))
expect(await listed.json()).toEqual({ count: 1 })
})
test("a body without text answers 400 and an unknown note 404", async () => {
expect((await callHandler(addNote, mockEvent("/api/notes", { body: {} }))).status).toBe(400)
expect((await callHandler(getNote, mockEvent("/api/notes/none", { params: { id: "none" } }))).status).toBe(404)
})
mockEvent("/api/greet?name=Ada")takes a path or aRequest.bodymakes the methodPOST, and an object or array is sent as JSON.paramsis whatgetRouterParamreads,contextis assigned ontoevent.contextandruntimeConfigis merged over the app's.callHandlerreads the input as the handler's route does, answers 400 with the issues when theinputschema refuses it, runs the handler's ownmiddlewareand turnscreateErrorandfail()into their status.- Any other throw answers the masked 500 of production and is not rethrown. To see the error itself, call the handler as a function:
await greet(input, { event }). useStoragereads memory mounts, one set for each test file, so aPOSTand a laterGETin the file see the same data. A test that needs clean data uses its own keys.- A websocket handler cannot be called this way. Test it against
setupwith aWebSocket. - To test the policies of an app that uses authorization, use
createAuthorizer: it checks one request against the entities you give, with no server and no database. See Test the policies. - To read the mail an app sent, use
sentMailof@hamur/mail/test, and for notificationssentNotificationsof@hamur/notifications/test. A test never sends: see Test the mail and Test notifications.
End-to-end tests
setup builds the app and serves it for the test file. Call it once, at the top level of the file.
import { $fetch, fetch, html, json, setup } from "hamur/test"
import { expect, test } from "bun:test"
setup()
test("the home page answers with its greeting", async () => {
const response = await fetch("/")
expect(response.status).toBe(200)
expect(await response.text()).toContain("<h1>Hello, Hamur</h1>")
})
test("$fetch returns the body of a route, with the value of .env.test", async () => {
expect(await $fetch("/api/greet?name=Ada")).toEqual({ hello: "Ada", from: "env-test" })
})
test("$fetch throws on an error status and fetch hands the status back", async () => {
await expect($fetch("/api/nope")).rejects.toMatchObject({ status: 404 })
expect((await fetch("/api/nope")).status).toBe(404)
})
test("html and json read the body of an answer", async () => {
expect(await html("/about")).toContain("About")
expect(await json("/api/forecast")).toEqual({ summary: "sunny" })
})
setup builds the app in place, as hamur build does, with buildDir and outputDir in a temp dir below node_modules/.cache of the app. No source file is written, and the temp dir is removed after the file. NODE_ENV stays test, so the $test block of the config applies.
server | What runs | fetch goes to |
|---|---|---|
"in-process" (default under bun test) | .output/server/index.mjs, imported into the test process | the handler, with no socket |
"bun", "node" | the output in a child process on a free port | http://127.0.0.1:<port> |
dev: true | hamur dev in a child process | the dev server |
The helpers are the same in every case.
fetch(path)returns theResponse. Use it when the test checks a status.$fetch(path)is the app's own$fetchand returns the body. It throws aFetchErroron a status of 400 or more, and afterhamur typegenit is typed by the route.html(path)andjson(path)read the body of an answer and check no status.url(path)gives the absolute URL. It needs a port:server: "bun","node",dev: true,browser: trueorport.getServerLogs()returns what a child process wrote. In process the app logs to the test's own output, so it throws.- Each helper joins a path below
app.baseURL, so a test does not repeat it.
A file with a second app uses buildModuleFixture. The teardown closes the pages, stops every child process, removes the temp dir and puts back the variables setup set, also after a failed or interrupted run.
.env.test, env and overrides
bun test sets NODE_ENV=test and reads .env, .env.test and .env.test.local of its directory. setup reads the same three files from rootDir, so the test app sees them whatever directory the run started in, and a value from the shell always wins.
GREETING_SOURCE=env-test
env sets variables over everything else, and overrides is merged over hamur.config.ts as the config's own blocks are.
import { $fetch, setup } from "hamur/test"
import { expect, test } from "bun:test"
setup({
env: { GREETING_SOURCE: "from setup" },
overrides: { runtimeConfig: { public: { site: "Overridden" } } },
})
test("env is set over the values of .env.test", async () => {
expect(await $fetch("/api/greet")).toEqual({ hello: "world", from: "from setup" })
})
test("overrides are merged over hamur.config.ts", async () => {
expect(await $fetch("/api/site")).toEqual({ site: "Overridden" })
})
dotenv: falseremoves every value Bun took from the files and reads none.dotenv: "extra.env"reads that file after the three, relative torootDir.modeadds.env.<mode>as--modedoes.- In process the values stay in
process.envfor the file; a child process gets them as its environment. overrides.buildDirandoverrides.outputDirare errors, since the build goes into a temp dir. Withdev: trueor under Vitest,overridesmust be JSON, so a function in it throws and names its path;overrides.modulestakes imported modules, which the child process imports again from their files.
Storage and time
storage: "memory" gives every storage mount of the app, its layers and its modules, and the default data mount, the memory driver for the test build. The config of the app is not changed, and a test writes nothing to disk.
useFakeTime moves the clock of the test process with setSystemTime of bun:test, so new Date(), Date.now() and Intl in your handlers read it, with server: "in-process".
import { $fetch, fetch, json, setup, useFakeTime } from "hamur/test"
import { expect, test } from "bun:test"
setup({ storage: "memory" })
test("a note is kept in memory", async () => {
const added = await fetch("/api/notes", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ text: "buy milk" }),
})
expect(added.status).toBe(200)
expect(await json("/api/notes")).toEqual({ count: 1 })
})
test("the app reads the fake clock", async () => {
const clock = useFakeTime(new Date("2030-01-01T00:00:00Z"))
try {
expect(await $fetch("/api/clock")).toEqual({ year: 2030 })
clock.advance(365 * 24 * 60 * 60 * 1000)
expect(await $fetch("/api/clock")).toEqual({ year: 2031 })
} finally {
clock.restore()
}
})
- The fake clock lasts until
restore(), and it is restored after the file. A seconduseFakeTime()beforerestore()throws. advance(ms)moves it forward, andset(time)to a time. Timers are not faked; usejest.useFakeTimersofbun:testfor them.- With a child process the app has its own clock, so
useFakeTimethrows and names theserveryou chose.
Browser tests
createPage opens a real browser on the test app. It needs a port, so call setup with browser: true, or with server: "bun", "node" or dev: true.
import { createPage, hasBrowser, setup } from "hamur/test"
import { expect, test } from "bun:test"
setup({ browser: true })
test.skipIf(!hasBrowser())(
"a click on a link shows the next page and the console stays clean",
async () => {
const page = await createPage("/")
try {
expect(await page.text("h1")).toBe("Hello, Hamur")
await page.click("a[href='/about']")
await page.waitFor("#about-title")
expect(await page.text("#about-title")).toBe("About")
expect(page.problems()).toEqual([])
} finally {
await page.close()
}
},
60_000,
)
hasBrowser() looks for a browser without starting one, so a file skips its browser tests where there is none.
createPage(path)opens a page and waits until it hydrated: the document is complete and the navigator stamped its history key. A page with no module script is ready at its load event.wait: "load"stops at the load event. Each wait lasts 10 seconds and then fails naming the path.- The page has
goto,back,forward,reload,click,type,press,evaluate,waitFor,text,html,screenshotandclose.clickandwaitForwait for the selector.typeinserts text and fires nokeydown; usepressto test keys. problems()lists the console errors, warnings and exceptions of the page, andconsoleMessagesandrequestshold everything. A client navigation renders afterclickresolves, so wait for the new page's selector.- The backend is Chrome through
Bun.WebViewon the main thread of Bun, and Hamur's own Chrome DevTools Protocol client ("cdp") elsewhere, such as under Vitest."webkit"is the system WebKit, on macOS only, and it records norequests. Every"chrome"page shares one profile andcreatePageclears the cookies and storage of the app first; two pages that need different cookies at once usebackend: "cdp". - Chrome is looked up in
BUN_CHROME_PATH,CHROME_PATH, the usual names onPATHand the macOS app bundles. Without one,createPagethrowshamur/test: no browser found; set BUN_CHROME_PATH or install Chrome.
The preload
The source place loads your files in the test process. hamur/test/preload does that for the whole run, and bunfig.toml names it.
[test]
preload = ["hamur/test/preload"]
The preload registers one plugin that loads the app's own files as the build would: the #hamur/* modules, the aliases, the import guards, the transform chain, and the compile step of the adapter (.vue, .svelte, Solid's JSX). It serves only files of the app's and its layers' srcDir and serverDir, never node_modules, a *.test.* file or .output/, so a test file is not transformed: it imports what it uses.
renderPage,renderComponentandmockComponentregister the plugin on their first call. A component you pass as a module path needs nobunfig.toml; a component the test file imports is loaded before any call, so it needs the preload when it has a compile step.HAMUR_TEST_ROOTis the app root (default the working directory), andHAMUR_TEST_TARGETisserver(default) orclient. One process serves one root: run the tests of another app in their ownbun test.- There is no DOM in the preload. An app that installed happy-dom lists
@happy-dom/global-registratorbeforehamur/test/preloadand setsHAMUR_TEST_TARGET=clientfor client code. - Nothing of the preload runs under Vitest.
Pages and components
renderPage and renderComponent render in the test process, through the app's adapter, and need neither setup nor a build.
import { registerEndpoint, renderComponent, renderPage } from "hamur/test"
import { expect, test } from "bun:test"
test("renderPage renders a page with the data of its loader replaced", async () => {
const page = await renderPage("/blog/ada", { data: { title: "Mocked", loadedAt: "now" } })
expect(page.status).toBe(200)
expect(page.html).toContain("<h1>Mocked</h1>")
expect(page.head).toContain("<title>Mocked</title>")
}, 60_000)
test("an unknown path renders the not-found page and threw nothing", async () => {
const page = await renderPage("/no-such-page")
expect(page.status).toBe(404)
expect("error" in page).toBe(false)
})
test("a page that throws gives the error page, its status and the thrown error", async () => {
const page = await renderPage("/boom")
expect(page.status).toBe(500)
expect((page.error as Error).message).toBe("boom")
})
test("renderComponent renders one component with its props", async () => {
const { html, status } = await renderComponent("app/components/Greeting.ts", { props: { name: "Ada" } })
expect(status).toBe(200)
expect(html).toContain("Hello, Ada!")
})
test("a registered endpoint answers the loader's fetch until it is removed", async () => {
expect((await renderPage("/forecast")).html).toContain("sunny")
const remove = registerEndpoint("/api/forecast", () => ({ summary: "stormy" }))
expect((await renderPage("/forecast")).html).toContain("stormy")
remove()
expect((await renderPage("/forecast")).html).toContain("sunny")
})
renderPage(path)matches the path with the app's routes and returnsstatus,headers,html(the whole document),head,payloadand, for a redirect,redirect.datareplaces the result of the page's loader, which then does not run; layout loaders still run.state,runtimeConfigandheadersset the render'suseStatevalues, runtime config and request headers. The route's middleware, loaders and access rules run;defineServermiddleware androuteRules()do not.renderComponent(component)renders one component inside the app context (plugins, config, head, state), as the only page of a route table, with no layout and no app root.componentis a module path from the app root or a component value, androuteandparamsare whatuseRoute()reads. It waits until the component's async data settled.- A render that threw answers as a request does:
htmlis the app's error page andstatusthe error's (500, or the status ofcreateError). The result also holdserror, the value that was thrown.erroris absent, notundefined, when nothing was caught. The app's logger writes one record to stderr, so a test of an error page prints one JSON line. registerEndpoint(path, handler)answers the request-bound fetch of a render (useFetch,$fetch, a loader'sfetch) before the app's routes.pathis a route pattern (/api/users/:id),methoddefaults to any, and the last registration wins. It returns a function that removes it, andonceanswers one request. A registration lasts until it is removed, or until the file ends.setup's test app never sees it: it is a bundle.
Component tests
@hamur/test-utils/<library> adds the helpers that need your library's types or its browser side: mountSuspended, renderSuspended and mockComponent. Import the entry of your app's framework; another one throws @hamur/test-utils: the app's framework is "vue"; import mountSuspended from "@hamur/test-utils/vue".
renderSuspended is renderComponent with props typed by the library. mountSuspended mounts a component on the client in a real browser, with the adapter's own mount, and resolves once the component and its async data settled. Its props travel as JSON, and its component is a module path.
Each sample below renders the counter on the server, then mounts it in a browser, clicks it and gives it new props.
React
import { hasBrowser } from "hamur/test"
import { mountSuspended, renderSuspended } from "@hamur/test-utils/react"
import { expect, test } from "bun:test"
import type Counter from "../app/components/Counter.tsx"
test("renderSuspended renders the counter on the server with its props", async () => {
const { html } = await renderSuspended("app/components/Counter.tsx", { props: { start: 3 } })
expect(html).toMatch(/<button[^>]*>(?:<!--[^>]*-->)*3(?:<!--[^>]*-->)*<\/button>/)
}, 60_000)
test.skipIf(!hasBrowser())(
"the counter mounted in a browser counts a click and takes new props",
async () => {
const counter = await mountSuspended<typeof Counter>("app/components/Counter.tsx", { props: { start: 0 } })
try {
expect(await counter.text()).toBe("0")
await counter.click("button")
expect(await counter.text()).toBe("1")
await counter.setProps({ start: 5 })
expect(await counter.text()).toBe("5")
} finally {
await counter.unmount()
}
},
120_000,
)
mountSuspended<typeof Counter> types the props of the component. Without C, props is any object.
Vue
import { hasBrowser } from "hamur/test"
import { mountSuspended, renderSuspended } from "@hamur/test-utils/vue"
import { expect, test } from "bun:test"
test("renderSuspended renders the counter on the server with its props", async () => {
const { html } = await renderSuspended("app/components/Counter.vue", { props: { start: 3 } })
expect(html).toMatch(/<button[^>]*>(?:<!--[^>]*-->)*3(?:<!--[^>]*-->)*<\/button>/)
}, 60_000)
test.skipIf(!hasBrowser())(
"the counter mounted in a browser counts a click and takes new props",
async () => {
const counter = await mountSuspended("app/components/Counter.vue", { props: { start: 0 } })
try {
expect(await counter.text()).toBe("0")
await counter.click("button")
expect(await counter.text()).toBe("1")
await counter.setProps({ start: 5 })
expect(await counter.text()).toBe("5")
} finally {
await counter.unmount()
}
},
120_000,
)
Preact
import { hasBrowser } from "hamur/test"
import { mountSuspended, renderSuspended } from "@hamur/test-utils/preact"
import { expect, test } from "bun:test"
test("renderSuspended renders the counter on the server with its props", async () => {
const { html } = await renderSuspended("app/components/Counter.tsx", { props: { start: 3 } })
expect(html).toMatch(/<button[^>]*>(?:<!--[^>]*-->)*3(?:<!--[^>]*-->)*<\/button>/)
}, 60_000)
test.skipIf(!hasBrowser())(
"the counter mounted in a browser counts a click and takes new props",
async () => {
const counter = await mountSuspended("app/components/Counter.tsx", { props: { start: 0 } })
try {
expect(await counter.text()).toBe("0")
await counter.click("button")
expect(await counter.text()).toBe("1")
await counter.setProps({ start: 5 })
expect(await counter.text()).toBe("5")
} finally {
await counter.unmount()
}
},
120_000,
)
Svelte
import { hasBrowser } from "hamur/test"
import { mountSuspended, renderSuspended } from "@hamur/test-utils/svelte"
import { expect, test } from "bun:test"
test("renderSuspended renders the counter on the server with its props", async () => {
const { html } = await renderSuspended("app/components/Counter.svelte", { props: { start: 3 } })
expect(html).toMatch(/<button[^>]*>(?:<!--[^>]*-->)*3(?:<!--[^>]*-->)*<\/button>/)
}, 60_000)
test.skipIf(!hasBrowser())(
"the counter mounted in a browser counts a click and takes new props",
async () => {
const counter = await mountSuspended("app/components/Counter.svelte", { props: { start: 0 } })
try {
expect(await counter.text()).toBe("0")
await counter.click("button")
expect(await counter.text()).toBe("1")
await counter.setProps({ start: 5 })
expect(await counter.text()).toBe("5")
} finally {
await counter.unmount()
}
},
120_000,
)
Solid
import { hasBrowser } from "hamur/test"
import { mountSuspended, renderSuspended } from "@hamur/test-utils/solid"
import { expect, test } from "bun:test"
test("renderSuspended renders the counter on the server with its props", async () => {
const { html } = await renderSuspended("app/components/Counter.tsx", { props: { start: 3 } })
expect(html).toMatch(/<button[^>]*>(?:<!--[^>]*-->)*3(?:<!--[^>]*-->)*<\/button>/)
}, 60_000)
test.skipIf(!hasBrowser())(
"the counter mounted in a browser counts a click and takes new props",
async () => {
const counter = await mountSuspended("app/components/Counter.tsx", { props: { start: 0 } })
try {
expect(await counter.text()).toBe("0")
await counter.click("button")
expect(await counter.text()).toBe("1")
await counter.setProps({ start: 5 })
expect(await counter.text()).toBe("5")
} finally {
await counter.unmount()
}
},
120_000,
)
text()andhtml()read the mount root, or a selector below it.clickandsetPropsresolve two animation frames and 50 ms after the change.unmount()removes the component and closes the page.- A mount takes 10 seconds at most to start and settle. Its error holds the page's console problems.
- The component's own server routes answer the page's requests, and
registerEndpointanswers first.
Replacing a component
mockComponent(path, replacement) replaces one component file of the app for the rest of the file, wherever it is imported. path is the file's path from the app root. replacement is a module path or a factory that returns the component or { default: component }.
import { renderComponent } from "hamur/test"
import { mockComponent } from "@hamur/test-utils/react"
import { expect, test } from "bun:test"
await mockComponent("app/components/base/Button.tsx", "test/mocks/BaseButton.tsx")
test("a component that imports the button gets the mock", async () => {
const { html } = await renderComponent("app/components/Card.tsx")
expect(html).toMatch(/mock:(?:<!--[^>]*-->)*Press/)
}, 60_000)
- It is async:
awaitit at the top of the file or inbeforeAll. A path that does not resolve throws@hamur/test-utils: mockComponent "app/components/x.tsx" does not resolve from <root>. - A module path works everywhere. A factory is a function of the test process, so it works in
renderPage,renderComponentandrenderSuspended;mountSuspendedthrows and asks for a module path. - The mock file is loaded with the app's build, so a
.vueor.sveltefile works, and it may import the original component.
Route stubs
createRouteStub makes a route table of its own and a start URL. renderComponent and mountSuspended take it as component, and it replaces the app's table for that render. Its loaders run in the test process.
import { createRouteStub, renderComponent } from "hamur/test"
import { expect, test } from "bun:test"
test("a route stub renders its route with the loader of that route", async () => {
const stub = createRouteStub(
[
{ path: "/", component: "app/components/Profile.tsx", load: () => ({ name: "Nobody" }) },
{
path: "/users/:id",
component: "app/components/Profile.tsx",
load: ({ params }) => ({ name: `User ${params.id}` }),
},
],
{ initialURL: "/users/7" },
)
const { html } = await renderComponent(stub)
expect(html).toContain("User 7")
}, 60_000)
Paths are checked as app/pages paths are. A path twice, and an initialURL that matches no route, throw. In mountSuspended every component of the stub is a module path, and a Link between two stubbed routes changes the shown route with no document request.
Module tests
A module author builds an app that uses the module and tests what it serves. buildModuleFixture(rootDir, options) is setup's build and serve without hooks: it returns the test app, and the test calls close(). It takes the options of setup and framework, so overrides can add a page or the module under test.
forEachAdapter(rootDir, body, options) reads the directories of rootDir named after the libraries (react, vue, preact, svelte, solid, html), builds each one and calls body(library, app) inside a describe of that name, so a failure names the library. No library directory throws.
import { buildModuleFixture, forEachAdapter } from "hamur/test"
import { afterAll, expect, test } from "bun:test"
const below = await buildModuleFixture(import.meta.dir + "/..", { overrides: { app: { baseURL: "/sub/" } } })
afterAll(() => below.close())
test("a second app of the file serves everything below its baseURL", async () => {
expect(await below.json("/api/forecast")).toEqual({ summary: "sunny" })
expect(await below.json("/sub/api/forecast")).toEqual({ summary: "sunny" })
})
forEachAdapter(import.meta.dir + "/fixtures", (library, app) => {
test(`${library}: the fixture's home page answers`, async () => {
const response = await app().fetch("/")
expect(response.status).toBe(200)
expect(await response.text()).toContain("Fixture")
})
})
A file calls setup once, and a second app in the same file comes from buildModuleFixture. Neither buildModuleFixture nor forEachAdapter registers a test app for the module-level fetch and useTestContext: the test calls the methods of the app it holds.
Vitest
hamur/test never imports vitest. Under Vitest, setup, its helpers, createPage, mockEvent and callHandler work, and the Vitest config needs globals: true.
export default { test: { globals: true } }
import { fetch, setup } from "hamur/test"
import { expect, test } from "vitest"
setup()
test("the home page answers", async () => {
expect((await fetch("/")).status).toBe(200)
})
- The build runs in a
bunchild process, sobunmust be onPATH, andoverridesmust be JSON. serverdefaults to"bun";"in-process"throws, and"node"needs a build with thenodepreset.createPageuses the"cdp"backend.- The source and browser places (
renderPage,renderComponent,mountSuspended,mockComponent,registerEndpoint) anduseFakeTimeneedbun testand throwhamur/test: <name> needs bun test.
Continuous integration
Browser tests skip where hasBrowser() is false, so a runner with no Chrome still passes the rest. To run them in CI, install Chrome and name it in BUN_CHROME_PATH.
name: test
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: oven-sh/setup-bun@v2
with:
bun-version: 1.4.4
- uses: browser-actions/setup-chrome@v1
id: chrome
- run: bun install --frozen-lockfile
- run: bun test
env:
BUN_CHROME_PATH: ${{ steps.chrome.outputs.chrome-path }}
Playwright against a build
hamur/test drives Chrome, and WebKit on macOS. For Firefox, for Playwright's traces and test runner, or for a suite that already exists, run Playwright against a build. Hamur has no entry that imports Playwright: it is your dev dependency, and Hamur only builds and serves the app.
bun add -d @playwright/test
bunx playwright install chromium
bun run e2e
The e2e script puts the hamur command on the PATH of the web server command.
{
"scripts": {
"e2e": "playwright test"
}
}
webServer runs hamur build && hamur preview, waits until url answers, and stops the server after the run. hamur preview serves a bun, node or static build on port 3000, or on the port in PORT or --port.
import { defineConfig, devices } from "@playwright/test"
export default defineConfig({
testDir: "e2e",
forbidOnly: Boolean(process.env.CI),
use: { baseURL: "http://localhost:3000" },
projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
webServer: {
command: "hamur build && hamur preview",
url: "http://localhost:3000",
reuseExistingServer: !process.env.CI,
timeout: 180_000,
},
})
import { expect, test } from "@playwright/test"
test("the home page links to the about page", async ({ page }) => {
await page.goto("/")
await page.getByRole("link", { name: "About" }).click()
await expect(page).toHaveURL("/about")
await expect(page.getByRole("heading", { name: "About" })).toBeVisible()
})
The server is the production build, so the test sees what a visitor sees. Set reuseExistingServer as you like: !process.env.CI keeps a running hamur preview for local runs and always starts a new one in CI. After a code change run hamur build again, since hamur preview serves the build and not the source.
What it does not do
- There is no DOM emulator and no helper that mounts into one. An app's own happy-dom works with the preload.
- Browsers are Chrome and macOS WebKit. Use Playwright for Firefox.
- There is no
server: "workerd"; a Workers app is tested on its own runtime. - A mock does not reach code inside a built bundle or a browser, except the file replacement of
mockComponent. - There is no Vitest environment and no source place under Vitest.
- There is no snapshot or visual-diff helper.
screenshot()returns the image, and comparing it is the test's job.
Every error of hamur/test starts hamur/test: and every error of @hamur/test-utils starts @hamur/test-utils: . The reference pages list them with their causes.