JavaScript如何实现单元测试_JavaScript测试框架Jest如何编写测试用例

JavaScript单元测试核心是独立可重复验证函数行为,Jest为主流框架;需安装配置、编写test/expect断言、处理异步、模拟依赖、用describe分组并规范命名。

JavaScript 单元测试的核心是:用独立、可重复的方式验证函数或模块的行为是否符合预期。Jest 是目前最主流的 JavaScript 测试框架,开箱即用、配置简单、API 清晰,特别适合初学者快速上手。

安装与基础配置

在项目中安装 Jest:

  • 运行 npm install --save-dev jest(或使用 yarn add --dev jest)
  • package.json 的 scripts 中添加:
    "test": "jest", "test:watch": "jest --watch"
  • 可选:添加 jest.config.js 配置文件,启用自动转换(如支持 import/export、JSX)、设置测试匹配规则等

编写第一个测试用例

假设你有一个计算两个数之和的函数 sum.js

function sum(a, b) { return a + b; }
module.exports = sum;

对应测试文件 sum.test.js(Jest 默认识别 *.test.js 或 *.spec.js):

const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
  • test() 定义一个测试用例,第一个参数是描述性文字,第二个是执行断言的回调函数
  • expect() 接收被测值,返回一个“期望对象”;toBe() 是匹配器(matcher),做严格相等(===)判断
  • 其他常用匹配器:toEqual()(深比较对象/数组)、toBeTruthy()toContain()toThrow()

测试异步逻辑与模拟依赖

遇到 Promise 或 API 调用时,Jest 支持多种处理方式:

  • 返回 Promise:在 test 回调中直接 return promise,Jest 会等待其 resolve
  • 使用 async/await(更推荐):
    test('fetches user name', async () => {
      const name = await fetchName();
      expect(name).toBe('Alice');
    });
  • 模拟函数行为:jest.fn() 创建模拟函数,配合 mockImplementation()mockReturnValue() 控制返回值
  • 模拟模块:jest.mock('./api') 替换整个模块,避免真实网络请求

组织测试与提高可维护性

describe() 对测试进行分组,提升可读性:

describe('math operations', () => {
test('adds positive numbers', () => { /* ... */ });
test('handles zero', () => { /* ... */ });
});

describe('user validation', () => {
test('rejects empty name', () => { /* ... */ });
});
  • 每个 describe 块可配 beforeEach()afterAll() 处理公共初始化/清理逻辑
  • 避免在测试中写业务逻辑,只关注输入→输出、副作用是否发生、错误是否抛出
  • 测试命名尽量具体:“should throw when email is missing” 比 “test invalid input” 更有用