Skip to content
Latchkey

Jest setupFilesAfterEnv Not Applied - Globals/Matchers Missing

Custom matchers (toBeInTheDocument) or global beforeEach hooks are undefined because your setup file never ran. Usually the path in setupFilesAfterEnv is wrong, or it was placed in setupFiles (which runs before the test framework exists).

What this error means

Tests fail with "expect(...).toBeInTheDocument is not a function" or your global hooks simply never fire. Importing the matcher directly in a single test works, proving the shared setup file is not being loaded.

Jest output
TypeError: expect(...).toBeInTheDocument is not a function

  > 6 |   expect(screen.getByRole('button')).toBeInTheDocument();
      |                                       ^

Common causes

Matchers placed in setupFiles, not setupFilesAfterEnv

setupFiles runs before the test framework is installed, so expect.extend (jest-dom) has no expect to attach to. Matcher setup must live in setupFilesAfterEnv, which runs after the framework loads.

Wrong path or overridden by a project config

A wrong <rootDir> path means the file is never found, or a projects[] entry overrides the root setupFilesAfterEnv so the root one is ignored for that project.

How to fix it

Register the setup file in the right key

Put framework-dependent setup (matchers, global hooks) in setupFilesAfterEnv.

jest.config.js
// jest.config.js
module.exports = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
};
// jest.setup.ts
import '@testing-library/jest-dom';

Verify the file actually loads

  1. Add a console.log in the setup file and confirm it prints once per worker.
  2. Check the <rootDir> resolves to where the file lives.
  3. For projects[], set setupFilesAfterEnv inside each project, not only at the root.

How to prevent it

  • Use setupFilesAfterEnv for anything that touches expect or test lifecycle.
  • Keep one shared setup module and reference it from every project.
  • Log from setup once to confirm it is wired in.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →