Jest with TypeScript
Jest runs tests. TypeScript types those tests if you compile them with ts-jest, babel-jest plus a preset, or by emitting first. Jest's own types (jest.fn, expect) live in @types/jest or in the jest package.
Detailed Explanation
A .test.ts file is a TypeScript file. Something has to strip types before Node runs it. ts-jest uses the TypeScript compiler and can type-check while transforming (isolatedModules: false). That is slow and correct. isolatedModules: true (the usual recommendation) transpiles per file and does not type-check. Pair it with tsc --noEmit in CI.
@types/jest gives you describe, it, expect, jest.fn. jest.fn() is jest.Mock<Return, Args> in older typings and a more specific Mock in newer ones. Untyped jest.fn() is a mock that accepts any arguments and returns any. That any will flow into the system under test and turn the test into a type hole.
Type a mock with the function you are replacing:
const find = jest.fn<UserRepo["find"]>();
find.mockResolvedValue(undefined);
Or jest.mocked(repo.find) after jest.mock to get a typed mock from the original. mockResolvedValue is only on mocks that return a promise; the types know that if the original return is Promise<T>.
Globals vs imports: modern Jest can import { describe, it, expect, jest } from "@jest/globals", which plays better with isolatedModules and ESM. The global style needs @types/jest in tsconfig types.
Path aliases in tsconfig paths are not visible to Jest unless you add moduleNameMapper. The types may resolve @app/foo in the editor and fail in Jest. Keep the maps aligned.
Do not use Jest as your only type test runner if you need expectError on types; tsd or Vitest's expectTypeOf are clearer. Jest is strong at runtime tests with typed mocks.
For Jest as a JS test runner (matchers, lifecycle), see the JavaScript Jest page. Here the work is ts-jest vs type-checking, and typing jest.fn.
Code Examples
1. A typed mock function.
// 1. A typed mock function.
type User = { id: string };
type Find = (id: string) => Promise<User | undefined>;
const find = jest.fn<Find>();
find.mockResolvedValue({ id: "u1" });
async function run(): Promise<string | undefined> {
return (await find("u1"))?.id;
}2. ts-jest transform; type-check stays in tsc.
// 2. ts-jest transform; type-check stays in tsc.
{
"preset": "ts-jest",
"testEnvironment": "node",
"globals": {
"ts-jest": { "isolatedModules": true }
}
}3. jest.mocked after jest.mock.
// 3. jest.mocked after jest.mock.
jest.mock("./repo.js");
import { repo } from "./repo.js";
const mocked = jest.mocked(repo);
mocked.find.mockResolvedValue(undefined);Common Gotchas
`jest.fn()` without a type returns `any`
pass the function type or wrap the original with `jest.mocked`.
`paths` need `moduleNameMapper`
editor success is not Jest success.
Mixing `@types/jest` globals with `@jest/globals` imports can duplicate types
pick one style.