jestjs/jest · error · Error
Do not import `@jest/globals` outside of the Jest test envir
Error message
Do not import `@jest/globals` outside of the Jest test environment
What it means
`@jest/globals` is a thin re-export module whose source ends in a top-level `throw new Error(...)` (index.ts:95). The actual exports are injected at runtime by jest-runtime, which replaces this module's namespace. If the module is evaluated outside a Jest worker (e.g. imported by a build tool, a Node script, or a non-Jest test runner), the throw fires and import fails by design.
Source
Thrown at packages/jest-globals/src/index.ts:95
*/
export type SpiedClass<T extends ClassLike> = JestSpiedClass<T>;
/**
* Constructs the type of a spied function.
*/
export type SpiedFunction<T extends FunctionLike> = JestSpiedFunction<T>;
/**
* Constructs the type of a spied getter.
*/
export type SpiedGetter<T> = JestSpiedGetter<T>;
/**
* Constructs the type of a spied setter.
*/
export type SpiedSetter<T> = JestSpiedSetter<T>;
}
export {jest};
throw new Error(
'Do not import `@jest/globals` outside of the Jest test environment',
);
View on GitHub (pinned to f49721c78e)
Solutions
- Only import `@jest/globals` from files that Jest executes; for shared helpers use the globals `jest`/`expect` injected onto the runtime instead.
- Conditionally import only when `process.env.JEST_WORKER_ID` is set.
- Split shared logic into a framework-agnostic module with no `@jest/globals` import.
- For bundlers, mark `@jest/globals` as external or exclude test files from the build.
Example fix
// before
import {expect} from '@jest/globals'; // imported by a Storybook preview
export function assertShape(x) { expect(x).toMatchObject(...); }
// after
export function assertShape(x) {
if (!process.env.JEST_WORKER_ID) return;
expect(x).toMatchObject(...); // uses the injected global
} Defensive patterns
Strategy: validation
Validate before calling
if (!process.env.JEST_WORKER_ID) {
throw new Error('this module may only be imported inside a Jest worker');
} Type guard
const isJestContext = () => Boolean(process.env.JEST_WORKER_ID);
Prevention
- Keep @jest/globals imports inside files only Jest runs.
- Mark @jest/globals external in bundler configs.
- Guard shared helpers with process.env.JEST_WORKER_ID.
When it happens
Trigger: `import {expect, jest} from '@jest/globals'` executed by anything other than jest-runtime: a Node REPL script, webpack/esbuild/rollup bundling the file, vitest/mocha loading the file, or a storybook preview that imports the test file.
Common situations: Sharing assertion helpers between Jest and a bundler; a storybook/addon that imports a file which transitively imports `@jest/globals`; running a migration spike with another runner; a config file accidentally imports a test file.
Related errors
AI-assisted analysis of jestjs/jest@f49721c78e (2026-08-03).
Data as JSON: /data/errors/79a76bcbae2951ee.json.
Report an issue: GitHub.