jest/prefer-importing-jest-globals

Require describe, test, expect and jest to be imported from @jest/globals

fixable

Jest puts describe, test, expect, jest and the hooks in the global scope of every test file, so nothing in the file says where they come from. An import from @jest/globals makes that explicit, and it brings the types with it.

Each file gets one report, which lists every name to import.

--fix adds the import, or adds the names to the @jest/globals import that's already there. In a .cjs or .cts file, and in a file that has no import or export yet, it writes const { .. } = require("@jest/globals") instead.

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"jest/prefer-importing-jest-globals" = "error" # or "warn"

Every option, set to its default. The ones that are commented out are unset by default.

bunfig.toml
[lint.rules]
"jest/prefer-importing-jest-globals" = ["error", {
  # types = <list of strings>,
}]

Examples#

example.ts1 problem
describe("cart", () => {
  test("starts empty", () => {
    expect(cart.items).toHaveLength(0);
  });
});
example.tsNo problems
import { describe, expect, test } from "@jest/globals";

describe("cart", () => {
  test("starts empty", () => {
    expect(cart.items).toHaveLength(0);
  });
});

Options#

OptionDefaultWhat it does
typesall of themThe kinds of globals to report: "hook" (beforeEach and the like), "describe", "test" (test and it), "expect", "jest", "unknown" (pending).

With { "types": ["jest"] }, you only need to import the jest object:

example.tswith { "types": ["jest"] }1 problem
jest.useFakeTimers();

test("expires", () => {
  expect(session.expired).toBe(false);
});
example.tswith { "types": ["jest"] }No problems
import { jest } from "@jest/globals";

jest.useFakeTimers();

test("expires", () => {
  expect(session.expired).toBe(false);
});

With { "types": ["unknown"] }, only pending is reported:

example.tswith { "types": ["unknown"] }1 problem
test("expires", () => {
  pending();
});