6 KiB
Testing
Tests use Node's built-in runner (node:test) and node:assert/strict, run
through tsx so they get the @server/*, @test/* and #dynamic/* aliases
from tsconfig.json. There is no test framework dependency.
Running
npm test # every server/**/*.test.ts and src/**/*.test.ts
npm run test:file -- server/lib/ip.test.ts # one or more files
npm run test:file -- --test-name-pattern="CIDR" server/lib/ip.test.ts
npm run test:watch
Run them from the repo root. They need the same setup as npm run dev:
npm run dev:setup (or the set:* scripts, a config/config.yml and
npm run db:push). test/setup.ts is preloaded into every test file. It
imports @server/extendZod like the app does on boot, and stops with a
message if the build files, the config or the SQLite database are missing.
Test files run one at a time (--test-concurrency=1) because the DB tests
share one database. The whole suite takes a few seconds.
--test-force-exit ends each file once its tests finish, so DB pools and
timers started by app modules don't hang the run.
CI (.github/workflows/test.yml) runs npm test on the OSS build with SQLite,
after db:generate and db:push.
Writing a test
Put <name>.test.ts next to the code it tests. The runner picks up any
*.test.ts under server/ or src/, including server/private/.
import { test } from "node:test";
import assert from "node:assert/strict";
import { hostCovers } from "./reservedHosts";
test("a wildcard covers one level of subdomain", () => {
assert.equal(hostCovers("*.example.com", "app.example.com"), true);
assert.equal(hostCovers("*.example.com", "a.b.example.com"), false);
});
- Import and test the real code. Don't paste a copy of the function into the test file, and don't assert against hard-coded lists that describe the code. A copy keeps passing after the real code changes. If a function can't be imported cleanly, move it into a small module that can (see below).
- Use
assert.equal/assert.deepEqual/assert.throws/assert.rejects/assert.match. They print a diff on failure. Pass a message only when the values alone don't say what went wrong. - Name each
test()after the behaviour it checks. Split unrelated checks into separate tests rather than one bigrunTests. - No
console.logprogress output and noprocess.exit. The runner reports results and sets the exit code. - Use
{ timeout: ms }on a test that could hang, andt.after()or thebefore/afterhooks to close servers and sockets you open. - For a test that needs something CI doesn't have (Redis, Docker), read the
setting from an env var and pass
{ skip: "set FOO to run" }when it is missing.server/private/wsGateway/gateway.test.tsis the example.
Import cycles
Some modules can't be imported first in a fresh process because of import
cycles between config, logger, db and the routers (for example
TraefikConfigManager.ts and anything that reaches routers/ws). The error
looks like Cannot read properties of undefined (reading 'getRawConfig') or
Cannot access 'X' before initialization. Don't work around it with import
order tricks in the test. Move the pure logic you want to test into its own
module with few imports and have the original file import it. Examples:
server/lib/traefik/wildcardCoverage.ts, server/lib/logRetention.ts,
server/lib/regionMatch.ts. Check both builds, because #dynamic changes the
import graph: npm run set:oss && npm test, then npm run set:enterprise && npm test.
Tests that use the database
A test may read and write the database the dev config points at (SQLite in
config/db/db.sqlite, or Postgres). It must never create, migrate, copy or
delete a database, and must not touch rows it didn't create. That database
holds the developer's own data, and other test files use it too.
- Create your own rows with ids from
testId()intest/db.ts. Thetest-prefix makes rows left by a crashed run easy to find. createTestOrg()/deleteTestOrg()give you an org. Hang everything else off it: deleting the org cascades to sites, resources, roles, AI providers and most other org-scoped tables. Delete anything outside the org yourself (exit nodes, domains, newts, rows inlogsDb, which can be a separate database on Postgres).- Never assume a table is empty. Scope every query and assertion to the ids
you created (
where orgId = yours,inArray(table.id, yours)), never a whole-table count. - Clean up in
after(), so it runs when an assertion fails as well. - Use only query-builder calls that exist on both drivers (
select,insert ... returning,delete)..get()/.all()are SQLite-only. - Don't call code that changes global state in ways the developer would
notice. If a function deletes or rewrites rows across the whole database
depending on config, test its decision as a pure function and only run the
real thing in a way that touches your own rows.
server/setup/copyInConfig.test.tsdoes this fordisable_config_managed_domains. - Call the real function in-process: middleware with a minimal
reqand anextthat records its argument (server/middlewares/verifySiteAccess.test.ts), outbound HTTP against a localhttp.createServeron port 0 (server/lib/deleteOrg.test.ts).
import { after, before, test } from "node:test";
import assert from "node:assert/strict";
import { db, sites } from "@server/db";
import { eq } from "drizzle-orm";
import { createTestOrg, deleteTestOrg } from "@test/db";
let orgId: string;
before(async () => {
orgId = await createTestOrg();
});
after(async () => {
if (orgId) await deleteTestOrg(orgId);
});
test("...", async () => {
await db.insert(sites).values({ orgId, niceId: "s", name: "s", type: "newt" });
const rows = await db.select().from(sites).where(eq(sites.orgId, orgId));
assert.equal(rows.length, 1);
});
To check that a run left nothing behind on SQLite:
sqlite3 config/db/db.sqlite "select orgId from orgs where orgId like 'test-%'"