Vitest 32 🧪 Global Stubbing — vi.stubGlobal and vi.stubEnv
Every test that touches a global is touching a process-wide singleton. fetch lives on globalThis, matchMedia lives on window, and process.env is one mutable object that the whole worker shares. Assigning to any of them directly — globalThis.fetch = vi.fn(), process.env.API_URL = "http://test" — works exactly once. The second test in the file inherits the mutated state, and the third inherits the second’s leftovers. There is no automatic rollback because plain assignment is invisible to the test runner.
vi.stubGlobal and vi.stubEnv are the tracked versions of that assignment. They record what the value was before they replaced it, so the runner can put it back. Everything else about them follows from that single design decision: they are not magic, they are bookkeeping.
This chapter covers the two stub functions, the missing-global case where no original exists, the dual target of vi.stubEnv (process.env and import.meta.env), the four ways to restore the original state, and the decision between stubbing, spying, and assigning.
Key point: vi.stubGlobal replaces or adds a property on globalThis and remembers the previous value, vi.stubEnv writes a key to both process.env and import.meta.env and remembers the previous value, and neither one undoes itself — the restoration is vi.unstubAllGlobals(), vi.unstubAllEnvs(), or the unstubGlobals and unstubEnvs config flags that run those calls before every test.
Why stubbing exists
The missing-global problem. Vitest’s default environment is Node, not a browser. IntersectionObserver, matchMedia, localStorage, and ResizeObserver simply do not exist there, so a component that calls one at construction time throws before any assertion runs. The options are to switch the whole file to jsdom — which is slow and drags in a full DOM you may not need — or to define the one global the test actually touches. vi.stubGlobal is the second option, and it works whether or not the name already exists.
The leak problem. A mutated global outlives the test that mutated it. vi.fn() installed on globalThis.fetch in test one is still installed in test two, and if test two never asserts on it, the stale mock quietly answers its requests. Real failures surface three tests later, far from the cause. Stubbing makes the mutation a named, reversible event rather than an anonymous side effect.
The spy limitation. vi.spyOn(globalThis, "fetch") is a good tool with a narrow contract: the property must already exist, must be a function, and must be writable. It cannot invent IntersectionObserver, it cannot replace a non-function value, and it leaves the spy installed until mockRestore() is called. Stubbing has no such requirement — it is a plain property write with a memory.
The env capture problem. Modules read process.env.X and import.meta.env.X when they are evaluated, not when they are used. A config module that computes const apiUrl = import.meta.env.VITE_API_URL at the top of the file has already captured the value by the time the first test body runs. Stubbing the variable afterwards changes what process.env reports but not what the module closed over. The stub is still correct — it is the timing that has to be understood.
The two-store problem. A single process.env.X = "y" does not change import.meta.env.X, and a single import.meta.env.X = "y" does not change process.env.X. Application code reads one or the other depending on whether it was written for Vite’s transform or for plain Node, and a test that only sets one of them passes or fails depending on which the module under test happens to read. vi.stubEnv writes both, which removes the ambiguity.
The parallel-worker problem. Vitest runs test files in separate workers, so a stub in one file does not reach another. That isolation is a feature, not a guarantee of correctness: within a worker, files may be reused, and within a file every test shares the same globalThis. The blast radius of an unstubbed global is the worker, not the test.
The trade-off. Stubbing is explicit, which means it is verbose: a stub, a restore, and a decision about scope for every global a file touches. The verbosity is the point. The alternative — one setupFiles entry that permanently fakes half the platform — is shorter and much harder to debug when a single test needs the real thing back.
a. vi.stubGlobal — replacing and creating globals
The signature is vi.stubGlobal(name: string, value: unknown), and it returns the vi instance so calls chain. It performs a property write on globalThis and, on the first stub of a given name, stores what was there before.
import { vi, test, expect } from "vitest";
// build the replacement first; a plain vi.fn() is not enough because the
// caller does `await fetch(...)` and then `res.json()`
const fetchMock = vi.fn(async () => ({
ok: true,
json: async () => ({ id: 1, name: "Alice" }), // the shape the caller expects
}));
// swap the global; the original fetch is remembered for restoration
vi.stubGlobal("fetch", fetchMock);
test("loads the profile", async () => {
const res = await fetch("/api/user/1"); // resolves to the stub
expect(await res.json()).toEqual({ id: 1, name: "Alice" });
expect(fetchMock).toHaveBeenCalledWith("/api/user/1"); // the mock recorded the call
});
The important detail is that stubGlobal itself is not a spy. It installs whatever value you hand it. Call history only exists because the value is a vi.fn(). Passing a plain object — vi.stubGlobal("navigator", { onLine: false }) — replaces the global with no recording at all, which is exactly right when the test asserts on behaviour rather than on calls.
The second case is a global that does not exist yet. There is no original to save, so unstubAllGlobals deletes the property instead of restoring it.
import { vi, test, expect, beforeEach } from "vitest";
// a minimal contract: only the members the component actually calls
class ObserverStub {
callback: IntersectionObserverCallback;
observe = vi.fn(); // the component calls this on mount
unobserve = vi.fn(); // and this on unmount
disconnect = vi.fn(); // and this in cleanup
constructor(cb: IntersectionObserverCallback) {
this.callback = cb;
}
}
beforeEach(() => {
// the name is absent in the node environment, so the stub creates it
vi.stubGlobal("IntersectionObserver", ObserverStub);
});
test("the observer is created and disconnected", () => {
const stop = mountCarousel(); // the component constructs the observer
expect(ObserverStub).toBeDefined();
stop(); // unmount runs the cleanup
});
A DOM environment deserves one warning. In jsdom and happy-dom, window is globalThis, so vi.stubGlobal("window", { ... }) replaces the object that every other global hangs off. Stub the member, not the container: vi.stubGlobal("matchMedia", ...) rather than a fake window.
// a partial matchMedia contract; libraries call anywhere from two to six of these
vi.stubGlobal("matchMedia", (query: string) => ({
matches: query.includes("dark"), // pretend the dark scheme is active
media: query, // echoes the query back
onchange: null, // required by the MediaQueryList type
addEventListener: vi.fn(), // the modern subscribe path
removeEventListener: vi.fn(), // the modern unsubscribe path
addListener: vi.fn(), // the legacy path some libraries still use
removeListener: vi.fn(),
dispatchEvent: vi.fn(),
}));
b. vi.stubEnv — environment variables in tests
The signature is vi.stubEnv(name: string, value: string). It writes the key to process.env and to import.meta.env in a single call, and it records the previous state of both. That dual write is the whole reason to prefer it over assignment: you do not have to know which of the two stores the module under test reads.
import { vi, test, expect } from "vitest";
test("the client points at the test api", () => {
// one call, both stores
vi.stubEnv("VITE_API_URL", "https://api.test");
expect(process.env.VITE_API_URL).toBe("https://api.test"); // node-style read
expect(import.meta.env.VITE_API_URL).toBe("https://api.test"); // vite-style read
});
process.env stores strings. Assigning a number or a boolean through Node’s env object yields the stringified form, so a variable that the application parses with Number(process.env.PORT) behaves the same whether the value came from the shell or from a stub. Pass the string the code expects and let it parse.
The common case is a branch flag. Code that reads process.env.NODE_ENV and takes an optimised path in production can be exercised without changing how the test suite itself is running.
import { vi, test, expect, afterEach } from "vitest";
test("logs the stack trace in production", () => {
vi.stubEnv("NODE_ENV", "production"); // flips the branch inside the logger
const output = formatError(new Error("boom"));
expect(output).toContain("at "); // the production path keeps the stack
});
afterEach(() => {
vi.unstubAllEnvs(); // puts NODE_ENV back where it was
});
The timing caveat is the one that costs people an afternoon. A module that reads the variable at evaluation time has already read it, and no stub performed afterwards can reach back into the closure.
// src/config.ts
// export const apiUrl = import.meta.env.VITE_API_URL; // captured once, at import
// src/config.test.ts
vi.stubEnv("VITE_API_URL", "https://api.test"); // too late for the cached module
The fix is to stub first and import second, which means the import has to happen after the mock in evaluation order — a dynamic import following a module-cache reset.
import { vi, test, expect } from "vitest";
test("reads the stubbed url at load time", async () => {
vi.stubEnv("VITE_API_URL", "https://api.test"); // written before the module exists
vi.resetModules(); // drop the cached config instance
const { apiUrl } = await import("./config"); // evaluated after the stub
expect(apiUrl).toBe("https://api.test");
});
c. Restoring — the two calls and the two config flags
vi.unstubAllGlobals() walks every name that was stubbed and puts back what was there. A name that existed is reassigned; a name that was invented is deleted. vi.unstubAllEnvs() does the same for every key touched by vi.stubEnv, on both stores.
import { vi, afterEach } from "vitest";
afterEach(() => {
vi.unstubAllGlobals(); // restore replaced globals, delete invented ones
vi.unstubAllEnvs(); // restore every key written by vi.stubEnv
});
Unstubbing is forgiving. Calling vi.unstubAllGlobals() when nothing was stubbed is a no-op, and stubbing the same name twice still restores the value that was in place before the first stub, because the original is captured once. What is not forgiving is expecting the other cleanup hooks to do this job: restoreMocks, clearMocks, and mockReset know nothing about stubs. A vi.fn() installed on globalThis is not a spy owned by the runner, so clearing mocks leaves it installed.
The two config flags fold the afterEach above into the runner, which is the right default for any project that stubs at all.
// vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
unstubGlobals: true, // call vi.unstubAllGlobals() before every test
unstubEnvs: true, // call vi.unstubAllEnvs() before every test
},
});
Note the wording: before every test, not after. The runner cleans up on entry rather than on exit, so a file whose last test throws still starts its next file in a clean state, and a stub declared at the top of a file survives exactly until the first test begins. That is why a vi.stubGlobal at module scope works at all — it is evaluated before the first cleanup — and why it must be re-established in a beforeEach if every test needs it.
Only vi.stubEnv is tracked. A plain process.env.DEBUG = "1" is invisible to vi.unstubAllEnvs() and will remain for the rest of the worker’s life.
process.env.DEBUG = "1"; // not tracked; survives unstubAllEnvs
vi.stubEnv("DEBUG", "1"); // tracked; restored by unstubAllEnvs
d. Choosing between stub, spy, and assignment
Three tools, three contracts. The choice is mechanical once the property is described: does it exist, is it a function, and does the test need to observe calls?
vi.spyOn replaces an existing method on an existing object and returns a spy that can undo itself with mockRestore(). It requires the property to be writable, which rules out the platform globals Node marks as read-only. It is the right tool when the test wants to keep the real object and observe one method on it.
import { vi, test, expect } from "vitest";
test("wraps the existing fetch", async () => {
// fetch exists in modern node and is writable, so a spy is allowed here
const spy = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("{}"));
await loadDashboard();
expect(spy).toHaveBeenCalledTimes(1);
spy.mockRestore(); // the spy owns its own teardown
});
vi.stubGlobal writes the property directly and takes responsibility for the original. It is the right tool when the name is missing, when the value is not a function, or when the replacement is a wholesale object.
// the name does not exist, so spyOn has nothing to attach to
vi.stubGlobal("IntersectionObserver", ObserverStub);
// the value is an object, not a method
vi.stubGlobal("navigator", { onLine: false, language: "en-GB" });
Plain assignment is the tool that has no teardown. It is occasionally the correct choice in a one-shot script and almost never the correct choice in a suite.
globalThis.fetch = vi.fn() as never; // nothing recorded the original; nothing restores it
Complete Example Session
// ============================================
// PART 1: THE FETCH STUB
// ============================================
import { describe, test, expect, beforeEach, afterEach, vi } from "vitest";
const fetchMock = vi.fn(async () => ({
ok: true,
json: async () => ({ id: 1, name: "Alice" }), // shape the caller destructures
}));
beforeEach(() => {
vi.stubGlobal("fetch", fetchMock); // installed fresh for each test
});
// ============================================
// PART 2: THE ASSERTION
// ============================================
test("loads the profile", async () => {
const user = await loadProfile(1);
expect(user.name).toBe("Alice");
expect(fetchMock).toHaveBeenCalledWith("/api/user/1"); // call recorded
});
// ============================================
// PART 3: THE MEDIA QUERY STUB
// ============================================
vi.stubGlobal("matchMedia", (query: string) => ({
matches: query.includes("dark"), // the component reads only this flag
media: query,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
}));
// ============================================
// PART 4: THE MISSING GLOBAL
// ============================================
class ResizeObserverStub {
observe = vi.fn(); // called on mount
unobserve = vi.fn(); // called on unmount
disconnect = vi.fn(); // called during cleanup
constructor(public callback: ResizeObserverCallback) {}
}
vi.stubGlobal("ResizeObserver", ResizeObserverStub); // added, not replaced
// ============================================
// PART 5: THE ENV STUB
// ============================================
test("reads both stores", () => {
vi.stubEnv("VITE_API_URL", "https://api.test"); // writes process.env and import.meta.env
expect(process.env.VITE_API_URL).toBe("https://api.test");
expect(import.meta.env.VITE_API_URL).toBe("https://api.test");
});
// ============================================
// PART 6: THE ENV READ AT IMPORT TIME
// ============================================
test("reads the url during module evaluation", async () => {
vi.stubEnv("VITE_API_URL", "https://api.test"); // set before the module exists
vi.resetModules(); // drop the cached instance
const { apiUrl } = await import("./config"); // evaluated after the stub
expect(apiUrl).toBe("https://api.test");
});
// ============================================
// PART 7: THE TEARDOWN
// ============================================
afterEach(() => {
vi.unstubAllGlobals(); // restores fetch, deletes ResizeObserver
vi.unstubAllEnvs(); // restores VITE_API_URL on both stores
});
// ============================================
// PART 8: THE CONFIG FLAGS
// ============================================
// vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
unstubGlobals: true, // vi.unstubAllGlobals() before every test
unstubEnvs: true, // vi.unstubAllEnvs() before every test
},
});
// ============================================
// PART 9: THE CHAINED STUBS
// ============================================
vi
.stubGlobal("fetch", fetchMock) // returns vi, so calls chain
.stubGlobal("navigator", { onLine: false }) // an object, not a function
.stubEnv("NODE_ENV", "production"); // and an env key in the same chain
// ============================================
// PART 10: THE SHARED HELPER
// ============================================
// test/helpers/browser.ts
export function stubBrowserEnv() {
vi.stubGlobal("matchMedia", (q: string) => ({ matches: false, media: q }));
vi.stubGlobal("localStorage", memoryStorage()); // a small in-memory shim
vi.stubEnv("VITE_API_URL", "https://api.test");
}
The ten parts covered the fetch stub, the call assertion, the media query stub, the invented global, the dual-store env stub, the import-time env read, the teardown, the config flags, the chained form, and a shared helper that installs the whole browser surface in one call.
Quick Reference
The Stub API
| Call | Writes to | Undone by |
|---|---|---|
vi.stubGlobal(name, value) | globalThis[name] | vi.unstubAllGlobals() |
vi.stubEnv(name, value) | process.env and import.meta.env | vi.unstubAllEnvs() |
vi.unstubAllGlobals() | restores or deletes every stubbed name | — |
vi.unstubAllEnvs() | restores every stubbed key | — |
Config Flags
| Option | Default | Effect |
|---|---|---|
unstubGlobals | false | vi.unstubAllGlobals() before every test |
unstubEnvs | false | vi.unstubAllEnvs() before every test |
clearMocks | false | clears calls; does not touch stubs |
restoreMocks | false | restores spies; does not touch stubs |
Stub, Spy, or Assign
| Tool | Needs the name to exist | Handles non-functions | Off by itself |
|---|---|---|---|
vi.stubGlobal | no | yes | no |
vi.spyOn | yes | no | yes, via mockRestore() |
| assignment | no | yes | no |
Globals Worth Stubbing
| Global | Typical environment |
|---|---|
fetch | node, for network isolation |
matchMedia | jsdom, for theme logic |
IntersectionObserver | node, missing entirely |
ResizeObserver | node, missing entirely |
localStorage | node, missing entirely |
navigator | node, for online and language checks |
crypto.randomUUID | node, for deterministic ids |
Best Practices
✅ Do This:
// Pass a vi.fn() when call history matters
vi.stubGlobal("fetch", vi.fn()); // ✅
// Stub the member, not the window container
vi.stubGlobal("matchMedia", fakeMatchMedia); // ✅
// Stub env before a dynamic import of a module that reads it
vi.resetModules(); await import("./config"); // ✅
// Restore in afterEach, or enable the config flags
afterEach(() => vi.unstubAllGlobals()); // ✅
// Use stubEnv so both stores are written
vi.stubEnv("VITE_API_URL", "https://api.test"); // ✅
// Keep the fake contract minimal but complete
({ matches: false, addEventListener: vi.fn() }); // ✅
❌ Don’t Do This:
// Assign directly and lose the original
globalThis.fetch = vi.fn() as never; // ❌
// Replace window in a jsdom environment
vi.stubGlobal("window", { fake: true }); // ❌
// Stub an env var after the module that reads it was imported
vi.stubEnv("VITE_API_URL", "x"); import "./config"; // ❌
// Expect clearMocks to remove a stub
clearMocks: true; // the stub is still installed // ❌
// Stub process.env directly and expect unstubAllEnvs to clean it
process.env.DEBUG = "1"; // ❌
// Return a partial fake missing a member the component calls
({ matches: true }); // addEventListener is undefined // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Mock survives into the next test | no unstubAllGlobals and no config flag | enable unstubGlobals |
x is not a function after stubbing | fake missing a method the code calls | complete the contract |
| Env stub ignored | module evaluated before the stub | stub first, then dynamic import |
import.meta.env.X unchanged | plain process.env assignment used | use vi.stubEnv |
| Entire DOM breaks | window itself replaced in jsdom | stub the member |
unstubAllEnvs does nothing | variable set by assignment, not stubEnv | use vi.stubEnv |
| Stub at module scope missing in test two | cleanup runs before each test | stub inside beforeEach |
| Spy fails on a platform global | property is not writable | use vi.stubGlobal |
Real-World Examples
1. Network isolation
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true, json: async () => ({}) }));
2. Theme detection
vi.stubGlobal("matchMedia", (q: string) => ({ matches: q.includes("dark"), media: q }));
3. Lazy loading
vi.stubGlobal("IntersectionObserver", class { observe = vi.fn(); disconnect = vi.fn(); });
4. Storage
vi.stubGlobal("localStorage", {
getItem: vi.fn(() => null), setItem: vi.fn(), removeItem: vi.fn(), clear: vi.fn(),
});
5. Connectivity
vi.stubGlobal("navigator", { onLine: false, language: "en-GB" });
6. Deterministic ids
vi.stubGlobal("crypto", { randomUUID: () => "00000000-0000-4000-8000-000000000000" });
7. Environment branch
vi.stubEnv("NODE_ENV", "production"); // exercises the optimised code path
8. Feature flag
vi.stubEnv("VITE_FEATURE_SEARCH", "true"); // the flag reader sees an enabled flag
9. Guaranteed cleanup
afterEach(() => {
vi.unstubAllGlobals();
vi.unstubAllEnvs();
});
10. Project-wide cleanup
test: { unstubGlobals: true, unstubEnvs: true }
Visual
The Stub Lifecycle
┌────────────────────────────────────────────────────────────┐
│ THE STUB LIFECYCLE │
│ │
│ before globalThis.fetch ──► real implementation │
│ │
│ stub vi.stubGlobal("fetch", mock) │
│ original saved ──► mock installed │
│ │
│ during globalThis.fetch ──► mock │
│ │
│ unstub vi.unstubAllGlobals() │
│ globalThis.fetch ──► real implementation │
└────────────────────────────────────────────────────────────┘
Existing Versus Missing
┌────────────────────────────────────────────────────────────┐
│ EXISTING GLOBAL MISSING GLOBAL │
│ │
│ fetch IntersectionObserver │
│ stub ──► replace stub ──► add │
│ unstub ──► restore unstub ──► delete │
└────────────────────────────────────────────────────────────┘
The Dual Write of stubEnv
┌────────────────────────────────────────────────────────────┐
│ vi.stubEnv("VITE_API_URL", "https://api.test") │
│ │ │
│ ┌─────────────┴─────────────┐ │
│ ▼ ▼ │
│ process.env import.meta.env │
│ "https://api.test" "https://api.test" │
│ │
│ vi.unstubAllEnvs() restores both │
└────────────────────────────────────────────────────────────┘
What Resets What
┌────────────────────────────────────────────────────────────┐
│ WHAT RESETS WHAT │
│ │
│ vi.unstubAllGlobals() only vi.stubGlobal entries │
│ vi.unstubAllEnvs() only vi.stubEnv entries │
│ globalThis.x = y nothing │
│ process.env.X = y nothing │
│ │
│ config: unstubGlobals / unstubEnvs │
│ runs before every test │
└────────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Replace a global | vi.stubGlobal(name, value) |
| Invent a global | same call; no original is saved |
| Replace an env var | vi.stubEnv(name, value) |
| Env targets | process.env and import.meta.env |
| Restore globals | vi.unstubAllGlobals() |
| Restore env | vi.unstubAllEnvs() |
| Auto-restore globals | unstubGlobals: true |
| Auto-restore env | unstubEnvs: true |
| Recording calls | pass a vi.fn() as the value |
| Not covered by cleanup | plain assignment |
Key takeaways:
- A stub is a tracked assignment.
vi.stubGlobalwrites toglobalThisand saves the previous value;vi.stubEnvwrites to both env stores and saves the previous value. Nothing else about them is special, which is why the restore step is mandatory rather than optional. - Missing and existing are different endings. A replaced global is restored on unstub; an invented global is deleted. Code that assumes the name exists after teardown will fail in the node environment and pass in jsdom.
stubEnvwrites both stores on purpose. Application code reads whichever one its build tool wired up, and a test that writes only one of them passes for reasons unrelated to the code under test.- The env capture problem is a timing problem. A module that reads a variable at evaluation time has already read it. Stub before the import, reset the module cache, and use a dynamic import to re-evaluate.
- The runner’s own cleanup does not know about stubs.
clearMocksandrestoreMocksoperate on spies the runner created. Avi.fn()installed as a global is nobody’s to clean up but yours. - Prefer the member over the container. In a DOM environment
windowisglobalThis, so replacing it replaces everything. StubmatchMedia, notwindow.
Remember: Globals and environment variables are the two pieces of state a test can mutate that the runner does not hand back automatically. vi.stubGlobal and vi.stubEnv make those mutations explicit and reversible, and unstubAllGlobals plus unstubAllEnvs — ideally through the config flags — are what keep a file from poisoning the next one in the same worker. Stub the narrowest thing, complete the contract the code actually calls, and always give it back.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!