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.
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
module.exports = {
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
};
// jest.setup.ts
import '@testing-library/jest-dom';Verify the file actually loads
- Add a
console.login the setup file and confirm it prints once per worker. - Check the
<rootDir>resolves to where the file lives. - For
projects[], setsetupFilesAfterEnvinside each project, not only at the root.
How to prevent it
- Use
setupFilesAfterEnvfor anything that touchesexpector test lifecycle. - Keep one shared setup module and reference it from every project.
- Log from setup once to confirm it is wired in.