Skip to main content
Lightning Jar - Web Studio Lightning Jar Wordmark

Findings No. 74

Bun's `mock.module` replaces a module for the whole test process, so one file's stub leaks into other files

bun test shares one module registry across files, so a mock.module stub leaks into other test files. Use spyOn on one export, or a child process.

Replicator Testing verified bun test, Bun 1.3 (replicator pins @types/bun 1.3.14)

Two projects hit this within a week.

In replicator, a new guard test reads the Drizzle schema's metadata and fails the build when a foreign key has no deletion handling. It passed when run alone and failed three ways in the full suite. Another test file uses mock.module to replace the schema module with stub tables. Read inside the shared test process, the schema reported zero foreign keys, and with zero foreign keys the coverage assertions would have passed while checking nothing.

In a client portal, one test file used mock.module to replace a whole module so it could stub one function. A new test in a different file dynamically imported the real module and failed with a "not a function" error on every run. Calling mock.restore() in afterAll did not help, because it runs after the colliding import has already resolved.

bun test runs every test file in one process with one module registry, and mock.module changes that registry for the whole process. Which version a given file sees depends on the order in which Bun loads the files.

The two projects fixed it differently. Replicator runs the guard in a child process, started with Bun.spawn on a helper script, so it reads the real schema whatever other files mock. The portal stopped replacing the whole module and patches the one export with spyOn(await import(mod), "fn"). ES module bindings are live, so the consuming module's own import sees the patch, and the module's other exports stay real for every other file.

General rule: treat mock.module under bun test as process-wide state. Patch single exports with spyOn, and run a test that must see real modules in its own process.

Receipt: replicator commit ea527d75 (tests/lib/server/fk-coverage.test.ts, tests/helpers/fkCoverage.run.ts; CHANGELOG 3.314.0), and a client project.

Ask Eljay

Ask about the studio's work, research, packages, or writing. A few starters:

Answers come from this site's own content and link their sources. For anything that matters, email hello@lightningjar.com.