TS + Webpack 整合 Jest
-
安装 Jest 和相关依赖
首先,安装 Jest 和 TypeScript 的 Jest 预处理器
ts-jest以及类型定义文件。npm install --save-dev jest ts-jest @types/jest -
初始化 Jest 配置
使用
ts-jest初始化 Jest 配置文件。npx ts-jest config:init这会生成一个基本的 Jest 配置文件
jest.config.js。如果没有生成,手动创建该文件并添加以下内容:module.exports = { preset: 'ts-jest', testEnvironment: 'node', moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], transform: { '^.+\\.(ts|tsx)$': 'ts-jest', }, testMatch: ['**/?(*.)+(spec|test).[tj]s?(x)'], }; -
配置 TypeScript
确保你的
tsconfig.json文件包含jest的类型定义:{ "compilerOptions": { "types": ["jest"] } } -
编写测试
在你的项目中编写测试文件,通常放在
__tests__目录或者与源文件同名但以.test.ts或.spec.ts结尾。例如,在src目录下创建example.test.ts:// src/example.test.ts import { myFunction } from './example'; test('myFunction should return correct value', () => { expect(myFunction(1)).toBe(2); });注意,要将测试文件或文件所在目录放在
tsconfig.json中指定的compilerOptions.rootDir下,不然会报Unable to process '...__tests__\utils.test.ts'之类的错误。 -
更新 npm 脚本
在
package.json中添加一个脚本来运行 Jest:{ "scripts": { "test": "jest" } } -
配置 ESLint
如果项目中使用了 ESLint,可能会提示 test 等函数未定义(no-undef),将下面的
overrides配置加到.eslintrc.js中可以解决:{ "overrides": [ { "files": ["**/?(*.)+(spec|test).[tj]s?(x)"], "env": { "jest": true } } ] } -
运行测试
运行以下命令来执行测试:
npm test
参考:ChatGPT、javascript - eslint throws `no-undef` errors when linting Jest test files - Stack Overflow
浙公网安备 33010602011771号