Jest · Unit tests that survive refactors
What are the key options in a Jest configuration?
Short answer
A Jest config controls roots, test matching, environment, transforms, module mapping and coverage. Keep it typed, put shared defaults in one file, and use projects for different runtimes.
Configuration is where the runner learns how to find, compile and run your tests. A small project needs very little. A monorepo usually needs projects, path mapping and a transform that matches the build setup. Keeping the config in a typed file catches mistakes before a test run.
import type { Config } from "jest";
const config: Config = {
testEnvironment: "jsdom",
roots: ["<rootDir>/src"],
testMatch: ["**/*.test.ts", "**/*.test.tsx"],
setupFilesAfterEnv: ["<rootDir>/src/test/setup.ts"],
moduleNameMapper: { "^@/(.*)$": "<rootDir>/src/$1" },
transform: { "^.+\\.tsx?$": "ts-jest" },
clearMocks: true,
restoreMocks: true,
};
export default config;Options worth knowing
testMatchandtestPathIgnorePatternsdecide which files are teststransformandtransformIgnorePatternsdecide what gets compiledmoduleNameMappermaps aliases and static assetssetupFilesandsetupFilesAfterEnvplace shared setup at the right timeclearMocks,resetMocksandrestoreMocksautomate cleanupprojectsruns several configurations in one command
Prefer a jest.config.ts or jest.config.js over the jest key in package.json once the config grows. You get comments, imports and type checking. If a setting seems ignored, check whether a project-level config overrides it, because project configs do not automatically inherit every root option.
npx jest --clearCache resolves many confusing stale results.Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between setupFiles and setupFilesAfterEnv?
- 2When should you use projects?
- 3Why does a config change sometimes require clearing the cache?
- 4What do clearMocks, resetMocks and restoreMocks each do?
Say it in the interview
A Jest config defines how tests are found, which environment they use, how files are transformed and how modules resolve. I keep it in a typed config file and use projects when a repo has both browser and server tests. I enable clearMocks and restoreMocks so cleanup is automatic. When a config change seems ignored, I check project overrides and clear the cache.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Jest mock interview and get scored feedback on depth, clarity and confidence.