ts-jest 的安装与使用
ts-jest 介绍
jest
是一款优雅、简洁的 JavaScript 测试框架。(棒读)
jest
只能测试 js 文件, 要对其他类型的文件进行测试, 则需要使用其他的扩展, 在typescript
项目中, 我们可以使用babel
或者ts-jest
来实现项目对ts
测试的支持.
拉取依赖
首先我们需要在项目中拉取相关的依赖:
# pnpm
pnpm add --save-dev jest ts-jest @types/jest
其中types/jest
是让编辑器的智能提示支持jest
类型.
配置
首先在package.json
中加入jest
的命令:
"scripts":{
/* ...其他命令... */
"test" :"jest",
/* ...其他命令... */
}
当然, jest
可以改为其他的内容.
然后在项目根目录下运行命令:
# pnpm
pnpm jest --init
就会在项目根目录下生成jest.config.js
配置文件.
我们可以把使用默认生成的配置文件或者改成ts
文件:
import type { JestConfigWithTsJest } from "ts-jest";
const jestConfig: JestConfigWithTsJest = {
preset: "ts-jest",
testEnvironment: "node", // 测试环境
};
export default jestConfig;
最后我们在tsconfig.json
内添加类型提示:
"compilerOptions"{
/*...其他配置... */
"types":["jest"]
/*...其他配置... */
}
这样就不会报错:Cannot find name 'test'. Do you need to install type definitions for a test runner? Try 'npm i --save-dev @types/jest' or 'npm i --save-dev @types/mocha' and then add 'jest' or 'mocha' to the types field in your tsconfig.
现在我们就可以在项目中使用jest
对ts
代码进行测试了!
注意
jest 默认运行**.test.js
的所有文件, 当然你也可以在jest.config.js/ts/json
文件对所需要运行的测试文件进行指定.