React + TS + Jest 环境搭建
约 480 字大约 2 分钟
2025-11-14
在 React + TypeScript + Jest + Vite 的开发环境中,如果使用路径别名(比如 @/),需要在每一个会处理代码的工具中都配置路径映射。
具体来说:
- TypeScript 编译器 (tsconfig.json / tsconfig.app.json)
- 配置 baseUrl 和 paths
- IDE 和类型检查需要这个
- Vite (
vite.config.ts)- 配置
resolve.alias - 打包和开发服务器需要这个
- 配置
- Jest (jest.config.ts)
- 配置 moduleNameMapper(用于运行时路径解析)
- ts-jest 的 tsconfig 中配置 baseUrl 和 paths(用于类型检查)
- 测试运行需要这个
它们互相不会继承配置,所以都需要单独配置。这样做的好处是每个工具可以有不同的策略,但代价就是配置重复。
npm create vite@latest my-appcd my-app
pnpm installpnpm install -D jest ts-jest @types/jest jest-environment-jsdompnpm install -D @testing-library/react @testing-library/jest-dom @testing-library/user-eventpnpm i --save-dev ts-node关键:@types/jest 不可少,否则 TypeScript 不知道 test, expect 等全局符号。
npm init jest@latest或者
npx ts-jest config:init配置 Jest jest.config.js:
export default {
preset: "ts-jest",
testEnvironment: "jsdom",
transform: {
"^.+\\.(ts|tsx)$": [
"ts-jest",
{
tsconfig: {
jsx: "react-jsx",
esModuleInterop: true,
baseUrl: ".",
paths: {
"@/*": ["src/*"],
},
},
},
],
},
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/src/$1"
},
setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
moduleFileExtensions: ["ts", "tsx", "js", "jsx"]
};jest.setup.ts:
import "@testing-library/jest-dom";在 tsconfig.json 或者 tsconfig.app.json (首选)配置::
"compilerOptions": {
// 关键:添加测试环境的类型声明
"types": ["vite/client", "jest", "@testing-library/jest-dom"]
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}说明:
types告诉 TS 额外引入全局类型:Vite、Jest、RTL- 避免
test is not defined或expect is not defined报错
tsconfig.app.json 和 tsconfig.json
测试
src/components/Hello.tsx
export default function Hello() {
return <h1>Hello Jest TS</h1>;
}src/components/Hello.test.tsx
import { render, screen } from "@testing-library/react";
import Hello from "./Hello";
test("renders hello", () => {
render(<Hello />);
expect(screen.getByText("Hello Jest TS")).toBeInTheDocument();
});{
"scripts": {
"test": "jest",
"test:watch": "jest --watchAll"
}
}注意:如果测试文件写在 src 外或者根目录,需要将 tsconfig.app.json 中 include 加上测试文件所在的文件件
vite 路径简写
import path from 'path'
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
}