Repository navigation
Conversation
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.
Collaborator
Author
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); });
The description lists what the change costs and the three options. CI: build 138086 is red for 28 test files, all |
Collaborator
Author
|
The body names the |
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Draft: the author of #44833 must decide.
Problem
vi.mock()factory reads a stalelet:let val = "first"; val = "second"; vi.mock("./dep.js", () => ({ v: val }))givesfirstat exit 0. Vitest 5.0.3 throwsReferenceError: Cannot access 'val' before initialization.is_primitive_literal_declaration(src/js_parser/lower/hoist_test_mocks.rs:223) moves a literalletabove the mocks. The write stays below the imports. No release has the rule.Fix
constonly. The plan runs before the visit pass finds a binding's writes.letduring the imports throws the existingReferenceErrorwith the hoisting note.test/js/bun/test/mock/mock-hoist.test.ts(45 new cases, main fails 33) andmock-module.test.ts. Self-reviewed: 25 concerns raised, 22 addressed (3 rejected, see Notes).Background
bun testmoves top-levelvi.mock()andjest.mock()calls above the file's imports, which becomeawait import(). So a factory runs before the rest of the file.lethoisted. All 2,741 sampled files give the same result.Downsides
let flag = false, assigned inbeforeEachand 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.mockModuledefers the error and the module stays real at exit 0. Main gives the mock. Merge this after that deferral is fixed.constonly, keep aletthat 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/letrule of #44833 ships, and this change then breaks a documented rule.The decision. #44833 hoists a literal
constand a literalleton purpose ("likebabel-plugin-jest-hoistdoes"). This PR withdraws thelethalf. The three shapes of a literalletthat a hoisted factory reads while it runs: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.tests/unit/tools/sast-scan.test.tsandsast-scan-rust.test.tsof ZaxbyHub/opencode-swarm (let mockSemgrepAvailable = false, read asavailable: mockSemgrepAvailablein the factory, assigned inbeforeEach). I ran a reduction of them, not the repository.constdoes not help them.vi.hoisted()or a read inside a returned function does.constthat is no literal. The same sample has 984 such reads in hoisted factories (915 of them inbun:testfiles).constonly: this PR.letunless 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 theletand is called at top level stays stale.letgives the factory its first value.bun test --aotneeds a second copy.Where the error is not reported.
let fake = "mocked"; vi.mock("./mod", () => ({ value: fake })), read by a test:const fake = String("mocked")await import()(the usual case)with { type: "json" })vi.mock(), abun:testfile imports itjest.mock(), a--preloadscript loaded the importermockModule(src/jsc/bindings/BunPlugin.cpp, "a hoisted factory that reads a variable declared below the call waits for the first import") clears theReferenceErrorand waits for an import that never comes.letto them. That deferral is not changed here. It needs its own fix.consttwin beside each. Anexport ... frombeside a lowered import gives theReferenceErrorwith the note (measured, not pinned).import deferwas not measured.Other effects.
constthat is no literal does the same on main.import.meta.glob()and a literallet: the glob entries load before the file's imports, as in a file with no literal declaration. On main theletmade them load after. A literalconststill does (parse_entry.rs, theimport_meta_glob_importsloop reads "hoisted_mocksis not empty" as "the file has a plan"). Reported separately.Existing cases that change. 5, all on the
lethalf of the rule:mock-hoist.test.ts:let fake = "fake"moves from the hoisted table to "stays in its place", andlet g = -2nbecomes aconst(both forjest.mockandvi.mock).mock-module.test.ts: the fixture of "jest.resetModules() keeps bindings already imported from a mock" incrementedlet calls = 0in a hoisted factory. It now usesvi.hoisted(). Its expectations are the same.var. Not changed. Avarisundefinedin 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 readsundefined, where it reads the assigned value if the file runs alone. That is the call timing ofmockModule, not a rule forvar.Measurements.
vi.mockandjest.mockfrombun:test,vitestand@jest/globals): 8 change against main. The 7 rows where main returns a value and Vitest and Jest both fail (a reassignedlet) are theReferenceErrorwith the note. Row 2 (let val = "a") is too.bun run, 0 of 1,065 underbun test. 9 of 26 modules with a hoist plan differ, and all 9 have a literallet..textis 110,627,497 bytes in both release builds. 2 symbols change size, the twoplan_mock_hoistinginstantiations: 1,140 to 1,137 bytes each.bun testprocess, 15 interleaved runs per release build, counted withperf_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,000letstatements: median 62,204,041 on main and 62,204,667 here (run-to-run range 923,000). A file with onevi.mock(): 14,905 per literalletstatement on main and 15,449 here (+544, range under 20). The statement now runs after theawait import(), like aletthat is no literal (15,829 on main).Suites run (debug build):
mock-hoist.test.ts177 pass.mock-module.test.ts307 pass, 1 todo.vitest-flavor.test.ts,mock-fn.test.js,transpiler-cache.test.ts,mock-module-non-string.test.tsandmock-module-resolve-log.test.ts1,079 pass.bun-test.test.tsandresolve-autoinstall-invalid-name.test.ts234 pass, 5 todo.isolation.test.ts,import-meta-glob.test.tsandplugins.test.ts814 pass, 7 time out, and the same 7 time out on a debug build of main.Self-review, rejected.
export defaultmovers on a hoist plan in this PR. That is a second change with its own compatibility question, and transpiler: keep a top-level class andexport defaultwhere they are written #46795 already proposes to remove those arms.bun lint --fixas the remedy for a never-assignedlet. I did not verify it.Not changed here.
export defaultalso move above the mocks (parse_entry.rs, thecan_be_moved()arms).class Fake { static v = "first" } Fake.v = "second"readsfirstin a hoisted factory on main and on this branch. transpiler: keep a top-level class andexport defaultwhere they are written #46795 (open draft) removes those arms.vi.hoisted()call moves whole, with its other declarators.bun test --aot: AOT: hangs, wrong answers, failed builds;bun test --aotfollows #44833's mocks #47605 and AOT: front end, test runs and tests for the rewritten compiler #47942 have a copy of the rule (VarKind::Const | VarKind::Letinsrc/aot/load/hoisted_mocks.rs). With option a they need the same narrowing.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