环境安装与配置
安装
安装jest
css
npm install --save-dev jest
配置package.json
命令
json
{
"scripts": {
"test": "jest"
}
}
配置
生成jest配置文件
kotlin
npm init jest@latest
jsdom测试环境需要安装jest-environment-jsdom
css
npm install --save-dev jest-environment-jsdom
使用babel
安装babel依赖
scss
npm install --save-dev babel-jest @babel/core @babel/preset-env
通过在项目的根目录中创建 babel.config.js
文件,将 Babel 配置为针对当前版本的 Node:
lua
module.exports = {
presets: [['@babel/preset-env', {targets: {node: 'current'}}]],
};
配置typescript支持
安装依赖
scss
npm install --save-dev jest typescript @types/jest @babel/core @babel/preset-env @babel/preset-typescript
jest
: Jest 测试框架本身。typescript
: TypeScript 编译器。@types/jest
: Jest 的类型定义文件。- Babel 相关依赖:用于将 TypeScript 转换为 JavaScript(Jest 默认不支持直接运行 TypeScript)。
配置
有两种主流的配置方式Babel
或 ts-jest
:
方式一:使用 Babel
- 创建
.babelrc
文件:
perl
{
"presets": [
["@babel/preset-env", { "targets": { "node": "current" } }],
"@babel/preset-typescript"
]
}
- 在
jest.config.js
中配置 Babel:
css
module.exports = {
transform: {
"^.+\.tsx?$": "babel-jest",
},
testRegex: "(/__tests__/.*|(\.|/)(test|spec))\.(jsx?|tsx?)$",
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
};
方式二:使用 ts-jest
- 安装
ts-jest
:
css
npm install --save-dev ts-jest
- 在
jest.config.js
中配置:
java
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
testRegex: "(/__tests__/.*|(\.|/)(test|spec))\.tsx?$",
};
配置 TypeScript
创建 tsconfig.json
文件(如果不存在):
json
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"esModuleInterop": true,
"strict": true,
"types": ["jest"]
}
}
报错处理
You appear to be using a native ECMAScript module configuration file, which is only supported when running Babel asynchronously or when using the Node.js --experimental-require-module
flag.
若 package.json
中包含 "type": "module"
,会强制项目使用 ES 模块,可能导致冲突:
json
{
"type": "module", // 如果存在此行,考虑移除或调整配置
"scripts": {
"test": "jest"
}
}
处理建议:
- 如果项目无需全局 ES 模块,移除
"type": "module"
。 - 如需保留,将 Babel 配置文件名改为
babel.config.cjs
(CommonJS 格式):
基础测试示例
基础断言/匹配器
常见匹配器
toBe
:用于判断基本数据类型是否相等。
toEqual
:用于判断对象或数组的内容是否相等。
toBeNull
:判断值是否为null
。
toBeUndefined
:判断值是否为undefined
。
toBeTruthy
:判断值是否为真值。
toBeFalsy
:判断值是否为假值。
toHaveLength
:判断数组或字符串的长度是否符合预期。
toHaveProperty
:判断对象是否具有某个属性。
scss
test('matcher examples', () => {
const num = 1;
const obj = { a: 1, b: 2 };
const arr = [1, 2, 3];
expect(num).toBe(1);
expect(obj).toEqual({ a: 1, b: 2 });
expect(null).toBeNull();
expect(undefined).toBeUndefined();
expect(true).toBeTruthy();
expect(false).toBeFalsy();
expect(arr).toHaveLength(3);
expect(obj).toHaveProperty('a', 1);
});
异步测试
pormise测试
kotlin
test('Promise 返回数据', () => {
return fetchData().then(data => {
expect(data).toBe('peanut butter');
});
});
async/await测试
scss
test('Async/Await 测试', async () => {
const data = await fetchData();
expect(data).toBe('peanut butter');
});
mock函数
模拟 API 调用、模块依赖等
scss
const mockFn = jest.fn();
mockFn.mockReturnValue(42); // 固定返回值
test('Mock 函数调用', () => {
expect(mockFn()).toBe(42);
expect(mockFn).toHaveBeenCalled(); // 验证是否被调用
});
钩子函数
在测试前后执行公共逻辑, 常用的钩子函数:beforeEach``afterEach``beforeAll``afterAll
scss
let data;
beforeEach(() => {
data = initializeData(); // 每个测试前重置数据
});
test('数据初始化', () => {
expect(data).toBeDefined();
});
快照测试
捕获组件或数据结构输出,防止意外修改,首次运行生成快照文件,后续测试对比变化.
scss
test('组件渲染快照', () => {
const component = renderer.create(<Button />);
expect(component.toJSON()).toMatchSnapshot();
});
型的快照测试用例渲染UI组件,拍摄快照,然后将其与测试旁边存储的参考快照文件进行比较。如果两个快照不匹配,则测试将失败