Skip to content

bun test: hoist a primitive-literal const with the mocks, not a let - #48045

Draft
robobun wants to merge 3 commits into
mainfrom
robobun/a8d4a4fe/hoist-literal-const-only
Draft

robobun wants to merge 3 commits into
mainfrom
robobun/a8d4a4fe/hoist-literal-const-only

Conversation

@robobun

@robobun robobun commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator

Draft: the author of #44833 must decide.

Problem

  • A hoisted vi.mock() factory reads a stale let: let val = "first"; val = "second"; vi.mock("./dep.js", () => ({ v: val })) gives first at exit 0. Vitest 5.0.3 throws ReferenceError: Cannot access 'val' before initialization.
  • is_primitive_literal_declaration (src/js_parser/lower/hoist_test_mocks.rs:223) moves a literal let above the mocks. The write stays below the imports. No release has the rule.

Fix

  • The rule accepts a const only. The plan runs before the visit pass finds a binding's writes.
  • A factory that reads a let during the imports throws the existing ReferenceError with the hoisting note.
  • Verified: test/js/bun/test/mock/mock-hoist.test.ts (45 new cases, main fails 33) and mock-module.test.ts. Self-reviewed: 25 concerns raised, 22 addressed (3 rejected, see Notes).

Background

  • bun test moves top-level vi.mock() and jest.mock() calls above the file's imports, which become await import(). So a factory runs before the rest of the file.
  • Considered a step after the visit pass that keeps a never-assigned let hoisted. All 2,741 sampled files give the same result.

Downsides

  • It breaks let flag = false, assigned in beforeEach and read while the factory runs. That passes on 1.4.2 and main. 2 of 2,741 sampled files have it, none the reported shape.
  • Where the mocked import stays static, mockModule defers the error and the module stays real at exit 0. Main gives the mock. Merge this after that deferral is fixed.
  • Question: const only, keep a let that no top-level statement assigns, or keep the rule with a docs line?
Notes

Origin. An automated fuzz run found the stale value. There is no issue and no user report. Without an answer before the next tag, the const / let rule of #44833 ships, and this change then breaks a documented rule.

The decision. #44833 hoists a literal const and a literal let on purpose ("like babel-plugin-jest-hoist does"). This PR withdraws the let half. The three shapes of a literal let that a hoisted factory reads while it runs:

shape sampled files (of 2,741) Bun 1.4.2 main this PR Vitest 5.0.3 Jest 30.5.2
never assigned 0 value value ReferenceError + note ReferenceError value
assigned again at top level (the reported shape) 0 last value first value ReferenceError + note ReferenceError transform error
assigned only in hooks, tests or the factory 2 first value first value ReferenceError + note ReferenceError transform error

The sample is 2,741 public test files with a hoisted mock call, from GitHub code search: 1,507 that import bun:test, 693 Jest and 541 Vitest files.

  • The two files are tests/unit/tools/sast-scan.test.ts and sast-scan-rust.test.ts of ZaxbyHub/opencode-swarm (let mockSemgrepAvailable = false, read as available: mockSemgrepAvailable in the factory, assigned in beforeEach). I ran a reduction of them, not the repository. const does not help them. vi.hoisted() or a read inside a returned function does.
  • bun test: Vitest compatibility #44833 already gives the same error to a const that is no literal. The same sample has 984 such reads in hoisted factories (915 of them in bun:test files).
  • Option a, const only: this PR.
  • Option b, keep hoisting a let unless a top-level statement assigns it: keeps the third shape and the first. It needs the place of each write from the visit pass and a step after it (not built). A function that assigns the let and is called at top level stays stale.
  • Option c, keep the rule: close this PR and state in the docs that a hoisted let gives the factory its first value.
  • The step after the visit pass (Background) restores only the first shape. It is not built. The estimate is about 45 Rust lines, and bun test --aot needs a second copy.

Where the error is not reported. let fake = "mocked"; vi.mock("./mod", () => ({ value: fake })), read by a test:

layout Bun 1.4.2 main this PR main with const fake = String("mocked")
the import becomes await import() (the usual case) mocked mocked ReferenceError + note ReferenceError + note
the file re-exports the import mocked mocked real, exit 0 real, exit 0
the import has attributes (with { type: "json" }) mocked mocked real, exit 0 real, exit 0
a helper module calls vi.mock(), a bun:test file imports it real mocked real, exit 0 real, exit 0
jest.mock(), a --preload script loaded the importer mocked mocked real, exit 0 real, exit 0
  • In the last four rows the module is already loaded when the hoisted call runs. mockModule (src/jsc/bindings/BunPlugin.cpp, "a hoisted factory that reads a variable declared below the call waits for the first import") clears the ReferenceError and waits for an import that never comes.
  • Main has these rows for every declaration that is no literal (last column). Vitest 5.0.3 throws in the second and third row. This PR adds the literal let to them. That deferral is not changed here. It needs its own fix.
  • The new cases pin these rows as they are, with the const twin beside each. An export ... from beside a lowered import gives the ReferenceError with the note (measured, not pinned). import defer was not measured.

Other effects.

  • When the module is already loaded and the file imports it later, the factory runs twice: once at the hoisted call, where the read fails, and once at the import. Main runs it once and reads the first value. A const that is no literal does the same on main.
  • A Vitest test file whose imports all stay static, with an eager import.meta.glob() and a literal let: the glob entries load before the file's imports, as in a file with no literal declaration. On main the let made them load after. A literal const still does (parse_entry.rs, the import_meta_glob_imports loop reads "hoisted_mocks is not empty" as "the file has a plan"). Reported separately.

Existing cases that change. 5, all on the let half of the rule:

  • mock-hoist.test.ts: let fake = "fake" moves from the hoisted table to "stays in its place", and let g = -2n becomes a const (both for jest.mock and vi.mock).
  • mock-module.test.ts: the fixture of "jest.resetModules() keeps bindings already imported from a mock" incremented let calls = 0 in a hoisted factory. It now uses vi.hoisted(). Its expectations are the same.

var. Not changed. A var is undefined in a factory that runs during the imports, as in Vitest 5.0.3, and "a var stays in its place" pins it. The docs now say so. When the module is already loaded, the factory runs at the hoisted call and also reads undefined, where it reads the assigned value if the file runs alone. That is the call timing of mockModule, not a rule for var.

Measurements.

  • existing cases changed: 5 (expected 5). test diff: +226/-6 lines.
  • launcher rows (26 shapes, vi.mock and jest.mock from bun:test, vitest and @jest/globals): 8 change against main. The 7 rows where main returns a value and Vitest and Jest both fail (a reassigned let) are the ReferenceError with the note. Row 2 (let val = "a") is too.
  • transpiled output: 0 of 1,064 modules without a hoisted call differ under bun run, 0 of 1,065 under bun test. 9 of 26 modules with a hoist plan differ, and all 9 have a literal let.
  • transpiler cache: 425 of 425 entries rebuilt on the first run, 0 on the second.
  • binary size: .text is 110,627,497 bytes in both release builds. 2 symbols change size, the two plan_mock_hoisting instantiations: 1,140 to 1,137 bytes each.
  • instructions: user-mode instructions of the whole bun test process, 15 interleaved runs per release build, counted with perf_event_open. valgrind is not available in the build container, so the plan alone is not isolated. A file with no hoisted call and 4,000 let statements: median 62,204,041 on main and 62,204,667 here (run-to-run range 923,000). A file with one vi.mock(): 14,905 per literal let statement on main and 15,449 here (+544, range under 20). The statement now runs after the await import(), like a let that is no literal (15,829 on main).

Suites run (debug build): mock-hoist.test.ts 177 pass. mock-module.test.ts 307 pass, 1 todo. vitest-flavor.test.ts, mock-fn.test.js, transpiler-cache.test.ts, mock-module-non-string.test.ts and mock-module-resolve-log.test.ts 1,079 pass. bun-test.test.ts and resolve-autoinstall-invalid-name.test.ts 234 pass, 5 todo. isolation.test.ts, import-meta-glob.test.ts and plugins.test.ts 814 pass, 7 time out, and the same 7 time out on a debug build of main.

Self-review, rejected.

  • Gate the class and export default movers on a hoist plan in this PR. That is a second change with its own compatibility question, and transpiler: keep a top-level class and export default where they are written #46795 already proposes to remove those arms.
  • Put the edits of the three existing cases in a commit of their own. The PR is squashed, and the list above names them.
  • Name bun lint --fix as the remedy for a never-assigned let. I did not verify it.

Not changed here.


no test proof · iteration 0 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/bun/test/mock/mock-module.test.ts

A top-level `let` with a primitive literal was hoisted above the mocks
and the lowered imports. A later write to it stayed in place, so a
hoisted `vi.mock()` / `jest.mock()` factory read the first value at
exit 0. The hoist plan runs before the visit pass and cannot know the
writes of a binding, so it now moves a `const` only.

A `let` that a hoisted factory reads during the imports is the same
ReferenceError with the note as any other declaration that stays in
place. The docs state what a `let` and a `var` give.
A `let` that only a hook assigns, the load orders where the module is
already loaded, and the layouts where the mocked import stays static.
The docs sentence now names the condition: a factory that runs during
the file's imports.
@robobun

robobun commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 4:07 PM PT - Nov 6th, 2026

❌ @robobun, your commit ca03c60 has 38 failures in Build #138086 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 48045

That installs a local version of the PR into your bun-48045 executable, so you can run:

bun-48045 --bun

@robobun

robobun commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: draft, waiting for a decision from the author of #44833

How I reproduced it, on a debug build of main b1305dd:

// dep.js
export const v = "real";

// a.test.js, run with: bun test ./a.test.js
import { test, vi } from "bun:test";
import { v } from "./dep.js";
let val = "first";
val = "second";
vi.mock("./dep.js", () => ({ v: val }));
test("t", () => { console.log("VALUE " + v); });
  • main prints VALUE first, 1 pass, exit 0. Bun 1.4.2 prints VALUE second. Vitest 5.0.3 and Jest 30.5.2 fail the file.
  • This branch fails the file with ReferenceError: Cannot access 'val' before initialization. and the hoisting note.
  • test/js/bun/test/mock/mock-hoist.test.ts: 33 of the 45 new cases fail on main, and all 177 cases pass on this branch.

The description lists what the change costs and the three options.

CI: build 138086 is red for 28 test files, all test/aot/* plus test/bundler/compile-aot-size.test.ts. The same files fail on main (build 137822). No lane reports a failure in mock-hoist.test.ts or mock-module.test.ts. On the ASAN lane they ran 177 and 307 passing cases.

@robobun

robobun commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator Author

The body names the import_meta_glob_imports loop in parse_entry.rs. #48141 moves that loop into place_import_meta_glob_imports (src/js_parser/lower/import_meta_glob.rs). The predicate that reads "hoisted_mocks is not empty" is unchanged there.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants