Test collection fails because script imports DB client at module scope (DATABASE_URL required at import time)
8febdd5e-078c-4a78-a8d1-ffb3e843bbf5
Cleanup/maintenance scripts in monorepos commonly import a shared DB client at module scope (e.g. import { dbClient } from '@org/db/client'). Vitest test files that import the script to unit-test pure helpers fail at COLLECTION TIME because the DB client module reads DATABASE_URL at import time and throws when unset.
Symptom: vitest reports "Error: DATABASE_URL is not set" with a stack trace pointing into the db client module even though no test exercises the DB code path.
This blocks unit testing of pure classifier/parser/predicate helpers. Workarounds (fake DATABASE_URL in CI, mocking the entire db module per test file) hide misconfiguration and pollute every test file.
main() function. Keep pure helpers (classifiers, parsers, predicate fns, template compilers) at module scope. Gate main() behind a module-as-CLI check.
// Pure helpers — safe to import in tests
export function classifyBody(body: string, templates: Template[]): 'system' | 'quarantine' { ... }
export function compileTemplate(kind: KindModule): Template { ... }
async function main(opts: { batchSize: number; dryRun: boolean }) {
// ALL db imports happen here, dynamically
const { dbClient } = await import('@org/db/client');
const { notifications } = await import('@org/db/schema');
// ... query/update logic
}
// CLI gate: ESM equivalent of CommonJS `require.main === module`
if (import.meta.url === `file://${process.argv[1]}`) {
main(parseArgs(process.argv)).catch(err => { console.error(err); process.exit(1); });
}Test file imports only the pure helpers — no DATABASE_URL needed, no mocks:
import { classifyBody, compileTemplate } from '../script.ts';Trade-off: dynamic await import() is slightly slower on first DB call, but it's one-time cost on a CLI script, not a hot path.
@org/db/client — the module's top-level code calls assertEnv('DATABASE_URL') which throws if unset. Because vitest imports the file under test to discover test names, the throw happens before any test code runs.
Alternatives considered:
- Mock entire db module per test file — works but brittle, every test file needs the mock.
- Set DATABASE_URL=fake in vitest config — hides real config errors elsewhere.
- Restructure imports so db only loads on actual CLI invocation — chosen.
import.meta.url === file://${process.argv[1]} is the ESM equivalent of require.main === module. Works under tsx/Node 20+.