跳到主要内容

jest 的使用

· 阅读需 1 分钟
泥豆君
哇!是泥豆侠,我们没救了

在 node 中使用 jest​

安装​

npm install --save-dev jest ts-jest @types/jest
npm install --save-dev jest-environment-jsdom jest-junit

初始化 jest 配置​

npx ts-jest config:init

生成的配置文件如下:

/** @type {import('ts-jest').JestConfigWithTSConfig} */
export default {
testEnvironment: "node",
- transform: {
- "^.+.tsx?$": ["ts-jest", {}],
- },
// 为了匹配我们的测试文件
+ testMatch: ['**/__tests__/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[tj]s?(x)'],
};

babel​

如果需要 babel 支持,可以安装 babel-jest 和 @babel/core 和 @babel/preset-env。

npm install --save-dev babel-jest @babel/core @babel/preset-env

创建测试文件​

touch test/test_name_.ts

编写测试代码​

跟据实际需求编写测试代码

运行测试​

npx jest

也可以将 jest 配置文件添加到 package.json 中,这样在运行测试时,就不需要每次都输入 npx jest 了

{
"scripts": {
"test": "jest"
}
}