当前位置 : 首页 » 文章分类 :  开发  »  JavaScript-Jest

JavaScript-Jest

JavaScript 测试框架 Jest 学习笔记

Jest 是由 Facebook 开发并维护的 JavaScript 测试框架。


安装 Jest

1、初始化 Node.js 项目

npm init -y

2、安装 Jest 和必要的 TypeScript 支持包

npm install --save-dev jest typescript ts-jest @types/jest

其中:

  • jest Jest 核心库
  • ts-jest Jest 的预处理器,用于在 Jest 中无缝编译和运行 TypeScript 测试代码。
  • @types/jest Jest 的类型定义文件,让 TypeScript 能理解 Jest 的 API (如 describe, it, expect)

jest.config.js 配置 Jest

执行 npx jest --init 交互式生成 jest.config.js 配置文件

// jest.config.js
module.exports = {
  // 预设环境
  preset: 'ts-jest',
  // 测试环境 (如果是 Node.js 后端项目,可以用 'node')
  testEnvironment: 'jsdom', // 或 'node'
  // roots 指定 Jest 搜索测试文件和模块的根目录(一个或多个)。
  roots: ['<rootDir>/src', '<rootDir>/tests'],
  // 告诉 Jest 处理哪些文件
  transform: {
    '^.+\\.(ts|tsx)$': 'ts-jest', // 用 ts-jest 处理 ts/tsx 文件
  },
  // 测试文件匹配模式 (通常放在 __tests__ 目录下或以 .test.ts/.spec.ts 结尾)
  testMatch: [
    '**/__tests__/**/*.+(ts|tsx|js)',
    '**/?(*.)+(spec|test).+(ts|tsx|js)'
  ],
  // 模块文件扩展名
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  // (可选) 设置别名映射 (如果你在 tsconfig.json 中配置了 paths)
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1', // 示例:将 @/ 映射到 src/
  },
  // 指定哪些源文件应该被收集覆盖率信息
  collectCoverageFrom: [
    'src/**/*.ts',
    '!src/**/*.d.ts',
  ]
};

Jest 测试文件

约定俗成,测试文件通常放在 __tests__ 目录下,或者与被测文件同名但以 .test.ts.spec.ts 结尾,并与被测文件放在同一目录。
例如有 src/math.ts

// src/math.ts
export function add(a: number, b: number): number {
  return a + b;
}

则对应的测试文件一般是:

  • src/__tests__/math.test.ts
  • src/math.test.ts

describe(name, fn) 将多个相关的测试用例分组。可以嵌套。
test(name, fn)it(name, fn) 定义一个单独的测试用例。it是 test的别名,源自 BDD (行为驱动开发) 风格。
expect(value) 开始一个断言。返回一个“期望对象”,可以链式调用匹配器 (Matcher)。
.toBe(expected) 一个​​匹配器​​。用于比较原始值 (数字、字符串、布尔值) 或检查对象引用是否相同。
.toEqual(expected) 对象或数组内容的比较

src/math.test.ts 测试文件:

// src/math.test.ts
import { add } from './math'; // 导入要测试的函数

// describe 定义一个测试套件 (一组相关的测试)
describe('add function', () => {

  // it 或 test 定义一个具体的测试用例
  it('adds two positive numbers correctly', () => {
    // 准备测试数据
    const num1 = 5;
    const num2 = 3;
    const expected = 8;

    // 调用被测函数
    const result = add(num1, num2);

    // 断言:验证结果是否符合预期 (Jest 内置 expect 断言库)
    expect(result).toBe(expected);
  });

  it('adds a positive and a negative number correctly', () => {
    expect(add(5, -2)).toBe(3); // 更简洁的写法
  });

  it('adds two negative numbers correctly', () => {
    expect(add(-1, -4)).toBe(-5);
  });
});

运行 Jest 测试

npm test 运行

在 package.json 的 scripts 中添加 test 命令,然后执行 npm test 即可执行 jest 测试,Jest 会自动查找所有匹配的测试文件并执行。

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

运行单个测试

运行单个测试文件:

npm test -- path/to/your.test.ts

运行匹配某个描述或测试名的测试:

npm test -- -t "adds two positive numbers" # 匹配测试名中包含该字符串的测试

VSCode 安装 Jest 插件

VSCode 安装 Jest 插件后,在测试文件的 describetestit 上会出现绿色的 ▶ 按钮,点击即可 Run Test 或者右键可 Debug Test,非常方便。


Vitest 测试框架

Vitest 一个新兴的、基于 Vite 的极速测试框架。它设计上兼容了大量的 Jest API,因此对于熟悉 Jest 的用户来说学习成本很低。
Vitest 充分利用了 Vite 的 ES Module 和原生 ESM 的优势,速度非常快。

特性:

  • 极快的速度:​​ 利用 Vite 的优化,热更新(HMR)测试体验极佳。
  • 与 Vite 配置共享:​​ 如果项目使用 Vite,配置可以复用,减少冗余。
  • 兼容 Jest API:​​ 大部分 Jest 的语法可以直接使用。
  • 原生 ESM/TypeScript 支持:​​ 对现代 JS/TS 项目非常友好。

下一篇 Aspose

阅读
评论
1.1k
阅读预计4分钟
创建日期 2025-09-16
修改日期 2025-09-16
类别

页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent:

评论