In Jest 30, what is the difference between setupFiles and setupFilesAfterEnv, and what can code in each one use?
answer
- before versus after the framework
- both run once per test file
- where expect.extend can live
- not the same as globalSetup
basics
~20 sBoth run before every test file. setupFiles runs first, inside the environment but before the test framework is installed, so expect, test and the hooks are undefined; setupFilesAfterEnv runs next and can call expect.extend or register afterEach.
solid answer
~40 sBoth keys list modules that Jest runs once **per test file**, inside that file's environment, before the file's own code. `setupFiles` runs first, before the test framework is installed: `expect`, `test`, `describe` and the hooks do not exist yet, so it suits environment preparation such as setting `process.env` values or adding a missing global. `setupFilesAfterEnv` runs after the framework is installed, so it can call `expect.extend` to add matchers and register `beforeEach` or `afterEach` hooks that then apply to every test in the file. Calling `expect.extend` from `setupFiles` fails with `ReferenceError: expect is not defined`. Neither is `globalSetup`, which runs once before all test files in a separate context whose globals the tests cannot read. A CommonJS setup module may export an async function, which Jest awaits.
code
javascript · 25 lines// jest.config.js
const {defineConfig} = require('jest');
module.exports = defineConfig({
setupFiles: ['<rootDir>/test/env.js'],
setupFilesAfterEnv: ['<rootDir>/test/after-env.js'],
});
// test/env.js: runs before the framework exists
process.env.API_BASE_URL = 'http://localhost:3000';
// test/after-env.js: expect and the hooks exist here
expect.extend({
toBeEven(received) {
const pass = received % 2 === 0;
return {
pass,
message: () => `expected ${received} ${pass ? 'not ' : ''}to be even`,
};
},
});
afterEach(() => {
jest.useRealTimers();
});go deeper
Recall that both lists run before each test file and that only setupFilesAfterEnv can use expect and the hooks.
Walk through the per-file order: environment, setupFiles, framework install, setupFilesAfterEnv, then the test file, and say what each step makes available.
Spot the production symptoms: a matcher registered too early, slow setup multiplied by file count, and globalSetup values the tests cannot see.
Decide what a team's shared setup may contain, keeping per-file setup small and moving run-wide resources to globalSetup so suite time stays predictable.
## Three places setup code can run Jest has three config keys that run code before tests, and they differ in **when** and **in which context** they run. | Key | How often | Context | Test framework available? | |---|---|---|---| | `globalSetup` | once per run, before all test files | outside the test files' environments | no; its globals are readable only in `globalTeardown` | | `setupFiles` | once per test file | inside that file's test environment | no: `expect`, `test` and hooks are undefined | | `setupFilesAfterEnv` | once per test file | inside that file's test environment | yes: globals, the `jest` object and `expect` | `setupFiles` and `setupFilesAfterEnv` both default to `[]` and take a list of module paths, usually written with the `<rootDir>` token. ## The order inside one test file For every test file, Jest does the following: 1. Creates the test environment named by `testEnvironment`, such as `node` or `jsdom`. 2. Runs each `setupFiles` module, in array order, inside that environment. 3. Installs the test framework: `describe`, `test`, the hooks and `expect` become available. 4. Runs each `setupFilesAfterEnv` module, in array order. 5. Runs the test file itself. Because a fresh environment is built for every file, both lists run again for every test file. They are not a once-per-run hook, and anything expensive in them is paid once per file. ## `setupFiles`: before the framework Use `setupFiles` for preparing the **environment** the code under test will see: - setting `process.env` values the application reads when it is imported; - adding a global the chosen environment lacks, through a small polyfill module; - configuring a library that must be set up before any module imports it. What is not there yet is the framework. In a run against Jest 30.5.2, `typeof expect`, `typeof test` and `typeof afterEach` were all `'undefined'` inside a `setupFiles` module, while the `jest` object was already present. A matcher registration placed here fails the whole file: ```plaintext ReferenceError: expect is not defined ``` ## `setupFilesAfterEnv`: after the framework Use `setupFilesAfterEnv` for code that would otherwise repeat at the top of every test file: - `expect.extend({...})` to register custom matchers, or a matcher library's registration; - `afterEach` or `beforeEach` hooks that should wrap every test, such as `afterEach(() => jest.useRealTimers())`, which is the example the Jest docs give; - shared cleanup a whole package agrees on. Hooks registered here are added at the top level of each test file, so they run around every test in it. Project-wide timer defaults have their own `fakeTimers` config key, covered with async testing, rather than a setup file. ## Async setup and other details - A **CommonJS** setup module may export an async function; Jest calls it and awaits the result. An **ES module** setup file can use top-level `await` for the same purpose. Both keys accept this. - The CLI flag `--setupFilesAfterEnv <path1> ... <pathN>` sets the second list from the command line. The CLI docs warn that files imported by the setup scripts will not be mocked during testing, so a module a setup file loads is not a reliable target for `jest.mock` in the tests. - In a `projects` config, put the lists in the project that needs them; a DOM matcher library belongs in the jsdom project, not in the API project. ## Choosing between them Ask three questions about the code you want to share: - **Does it call `expect`, `test` or a hook?** Then it can only live in `setupFilesAfterEnv`, because those globals do not exist earlier. - **Does it only prepare globals or environment variables that the code under test reads?** `setupFiles` is enough, and it keeps that preparation separate from assertion helpers. - **Should it happen once for the whole run, such as starting a shared server?** Neither list fits; that is `globalSetup`, paired with `globalTeardown`. When both lists are used, keep each file small and named for its job, because every test file pays for both. ## Mistakes interviewers listen for - Calling `expect.extend` or registering `afterEach` in `setupFiles`. - Treating either list as once per run, then being surprised that a slow setup multiplies by the number of test files. - Using `globalSetup` to create a global for the tests; its globals are only readable in `globalTeardown`. - Expecting a setup file to change the environment, which was created before it ran.
- A Jest 30 suite registers a custom matcher in setupFiles and every file fails before its first test; why?`setupFiles` runs before the test framework is installed, so `expect` does not exist yet and `expect.extend` throws `ReferenceError: expect is not defined`. Move the registration to `setupFilesAfterEnv`, which runs after `expect`, the globals and the hooks are in place.
- How does globalSetup differ from both setup lists?`globalSetup` names one module exporting a function that runs once before all test files, not once per file. It does not run inside a test file's environment, and globals it defines can only be read in `globalTeardown`. Use it for run-wide resources such as starting a server, then hand details to the tests through something like `process.env`.
- What is the cost of heavy work in setupFilesAfterEnv in a large suite?It runs once for every test file, inside each file's fresh environment, so its cost is multiplied by the number of files. Keep it to registrations and light hooks, and move one-time work such as starting a shared service to `globalSetup`.
- setupFiles and setupFilesAfterEnv both run once for the whole test run.
- expect.extend can go in setupFiles because expect is a global from the start.
- setupFilesAfterEnv runs after each individual test, as a teardown step.
- Globals set in globalSetup are readable inside every test file.
- A setup file can switch the test environment from node to jsdom.