Jest · Unit tests that survive refactors
How do transforms work in Jest?
Short answer
Jest runs files through a transform before executing them, which is how TypeScript and JSX become runnable JavaScript. Use ts-jest or babel-jest and keep the transform consistent with your build.
Jest does not strip types or compile JSX on its own. A transform receives the file source and returns JavaScript that Node can execute. The transform also handles hoisting for jest.mock, which is why the Babel plugin for Jest matters when you customise Babel.
export default {
transform: {
"^.+\\.tsx?$": [
"ts-jest",
{
tsconfig: "<rootDir>/tsconfig.test.json",
diagnostics: { warnOnly: false },
},
],
},
transformIgnorePatterns: ["/node_modules/(?!some-esm-package)"],
};Choosing a transform
ts-jesttype-checks and compiles TypeScript, useful for catching type errors in testsbabel-jestis faster and aligns with a Babel build, but it does not type-check@swc/jestis a fast Rust-based alternative for large suites- A custom transform should stay small and deterministic
Type checking in the test runner duplicates a tsc --noEmit step but catches test-only mistakes. Many teams disable ts-jest diagnostics and rely on a separate typecheck for speed. Either choice is valid if CI actually runs the type checker somewhere.
jest.mock not hoisting. When behaviour differs between the app and tests, compare the Babel and TypeScript configuration used by each.Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between ts-jest and babel-jest?
- 2Why does jest.mock hoisting depend on the transform?
- 3When would you use @swc/jest?
- 4Why might tests and the app compile differently?
Say it in the interview
Jest transforms each file before Node runs it, which is how TypeScript and JSX work at all. I use ts-jest when I want type checking in the test run, or a faster transform with a separate typecheck step. The transform also handles jest.mock hoisting, so I keep its Babel or TypeScript settings aligned with the app. When app and test behaviour diverge, the transform configuration is the first thing I compare.
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.