# ts-jest-practice **Repository Path**: anuoxiang/ts-jest-practice ## Basic Information - **Project Name**: ts-jest-practice - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-06-08 - **Last Updated**: 2024-06-08 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # TypeScript项目应用Jest实践 我们的项目已经由javascript全面转为TypeScript,这并不代表TypeScript比JavaScript更优秀。而是随着项目规模和参与开发的团队规模的扩大,类型约束对项目的质量有非常明显的帮助。 ## 开始 项目初始化,对于TS的项目,Jest支持两种方案:babel或ts-jest,这里选择ts-jest。安装jest以及依赖: ```Shell mkdir your-project npm init -y tsc init pnpm add --save-dev jest ts-jest @types/node @types/jest @jest/globals ``` ## 配置 ### Jest > npx ts-jest config:init 初始化配置文件,也可以运行 > npx jest --init ```Shell ❯ npx jest --init The following questions will help Jest to create a suitable configuration for your project ✔ Would you like to use Typescript for the configuration file? … yes ✔ Choose the test environment that will be used for testing › node ✔ Do you want Jest to add coverage reports? … yes ✔ Which provider should be used to instrument code for coverage? › v8 ✔ Automatically clear mock calls, instances, contexts and results before every test? … no ``` 建议采用后者,因为后者创建的配置文件中包含全部的配置以及解释,不用到的配置也被注释掉,方便调整。再打开配置文件,调整常见开发环境下的测试特性: 1. 忽略测试目录:因为用TS,有些项目会先构建dist目录,然后运行,所以需要把dist目录忽略掉。testPathIgnorePatterns:["/node_modules/","/dist"] 2. 设置转义,ts扩展名的文件,用ts-jest处理。transform:{"^.+\\.(t|j)s$": "ts-jest"} ### Package.json 修改tsconfig.json:输出目录outDir设置为./dist,(如有)设置.gitignore的忽略目录 ## 实践 略,具体查看源代码 ## 丝滑设置 以上的项目仅能保证在初始化时可以用,而实际的项目很少有如此简单的。比如说项目中会用到很多本地类库,由于路径复杂,往往会设置别名(Alias),此时必须同步tsconfig和jest.config两者的配置。例如tsconfig.json有: ```Json "paths": { "src/*": ["./src/*"], "common": ["./src/common"] } ``` 创建src/common/index.ts并输入简单的内容,验证是否能被加载到即可。此时,如果不做任何操作,程序可以被正确构建,但是无法通过jest,因为此时的jest,还无法正确识别common。所以需要在jest.config.ts中加入: ```TypeScript // …… 其他内容 moduleNameMapper: { "^common$": "/src/common", }, // ……其他内容 ```