Test-suite gotchas — institutional memory
Every entry below cost real debugging time once. Scan before diagnosing a weird failure; append new entries (symptom → cause → fix) when you burn time on something not listed.
Mocking
- Mock-specifier collision (
./xvs./x.js) — symptom:[vitest] No "<name>" export is defined on the "../lib/x.js" mock. Both specifiers resolve to ONE module; if two files import it differently and you declare twovi.mocks, the first wins and the other import gets a mock missing its exports. Declare ONE mock (either specifier) carrying ALL exports any importer needs. (Hit in caseLaw.test.ts with userSettings.) - Blanket getConfig mocks create phantom secrets — symptom: expected
object suddenly contains extra keys filled with your test secret.
getConfigMock.mockResolvedValue(SECRET)answers EVERY secret name, and code paths likeresolveSecret("openrouter-api-key")route through getConfig. Use a name-awaremockImplementationthat resolves only the names under test and rejects the rest. (Hit in userApiKeys.test.ts.) - instanceof across mocked modules — a route's
err instanceof McpOAuthRequiredErrorworks with a fake class ONLY because the route imports the class from the same mocked module the test constructs it from. Define the fake class insidevi.hoisted()and export it from thevi.mockfactory. (user.test.ts MCP block.) - Partial mocks:
vi.mock(import("../lib/x"), async (importOriginal) => ({ ...(await importOriginal()), oneFn: mock }))— used for userDataCleanup so per-resource routes keep the real helpers. - Engine mock bypassed by the altien import cycle — symptom: a route
test mocks
modules/chat/engine/indexyet handlers run the real engine (500s likedocs.map is not a function). Cause: Dev-onlyaltien/externalSources/chatDispatchervalue-importschat.service, which the engine's toolDispatcher loads while the engine mock factory is still resolving, sochat.service/chat.preparebind the real engine. Fix:import "../../modules/chat/chat.service";beforebuildApp(chat.routes.test.ts) or mockchat.servicetoo (projectChat.routes). - Upstream route suites assume
app+ bare paths — Dev's app.ts exportsbuildApp()and mounts every router under/api/...; adapt withconst app = buildApp()and explicit/apipaths. - Azure SDK dynamic imports are mockable —
vi.mock("@azure/keyvault- secrets", ...)interceptsawait import(...)in initDownloadSigningSecret. No special handling needed.
Runtime / interop
- tsx compiles repo TS as CommonJS (tsconfig
module: CommonJS): child processes that dynamic-import repo modules get named exports under.default. Use(mod.default ?? mod).fn. (Child-server test in downloadTokens.test.ts.) - Crash/exit behaviour can't be tested in-process — the runner owns
unhandledRejection. Spawn a child (
node --import tsx --input-type=module -e "<code>") and assert on exit codes / continued serving. - Don't emit real process events to test process guards — grab the
newly-registered listeners via
process.listeners()diffing and call them directly; remove them in afterEach. (processGuards.test.ts.) URL.hostnamekeeps brackets on IPv6 literals —https://[::1]/gives hostname"[::1]", sonet.isIP()misses it and it goes down the DNS path. Mockdns/promisesaccordingly. (client.test.ts SSRF.)- supertest is lazy — a
request(app).post(...)chain does nothing until.then/await. For concurrency tests wrap each inPromise.resolve(...)to fire it eagerly, then release your gate. (caseLaw in-flight dedup test.) - userEvent.click on a disabled button throws — assert
toBeDisabled()first and.catch(() => {})the click.
Suite / environment
- pnpm allowBuilds gate — new devDeps with postinstall scripts (msw)
fail install with
ERR_PNPM_IGNORED_BUILDSuntil allowed in the package'spnpm-workspace.yamlallowBuilds:map. - Env leakage between tests — module-level key caches
(userApiKeys/mcp client
flushEncryptionKey-style) and process.env both persist across tests in a file. Flush caches in beforeEach and snapshot/restore every env var you touch. - vitest.config uses
vite-tsconfig-pathsplugin — vite now warns it's native (resolve.tsconfigPaths: true). Works fine today; if the warning becomes an error on a vite upgrade, swap plugin → native flag in BOTH package configs and drop the dep. tsc --noEmitis a separate gate — vitest transforms with oxc and never type-checks; 3 type errors shipped invisibly until tsc ran. CI or pre-commit should run both.- Writing test files via bash heredocs mangles
\nescapes on this Windows setup — a"data: [DONE]\n\n"literal arrived as real newlines and broke the parse. Write test content with the Write/Edit tools, notcat <<EOF. - jsdom + portals — createPortal components (Modal, popups) render
into document.body; RTL
screenqueries find them, butcontainer-scoped queries do NOT. Query viascreen.
Adaptation rules (drift after syncs/backports)
- Route handlers that time out at exactly the test timeout = hung request = escaped async rejection (issue-041 class). Product bug; fix the route.
- Supabase fluent chains grow (
.is(),.filter(),.upsert()): update the test's fake builder, and prefer migrating the file tosrc/test/helpers/fakeDb.tsover patching one-off fakes. - Provider/model lists churn (
ALLOWED_MODEL_IDS, OPENAI_LOW_MODELS): test against stable invariants (aoai: prefix always allowed; mock the list) instead of hard-coding model ids. - Field renames arrive from upstream (
display_name→filename): checkgit log -S<old-name>before assuming the test is right.