ToolkitX
知识库工具箱

测试与部署

Jest, Supertest, PM2 部署

25min·进阶

01. Jest 基础

Jest 是 Facebook 开发的 JavaScript 测试框架,内置断言库、Mock、覆盖率报告等功能。
javascript
// math.test.js
import { add, divide } from "./math.js";

describe("数学函数", () => {
test("add 正常相加", () => {
    expect(add(2, 3)).toBe(5);
});

test("divide 除以零抛出错误", () => {
    expect(() => divide(10, 0)).toThrow("除数不能为零");
});
});

// 运行测试
// npx jest
// npx jest --watch

02. Mock 与异步测试

Mock 用于模拟依赖,隔离被测试代码。Jest 提供了强大的 Mock 功能。
javascript
// Mock 函数
const mockFn = jest.fn();
mockFn("hello");
expect(mockFn).toHaveBeenCalledWith("hello");

// Mock 返回值
const mockFetch = jest.fn();
mockFetch.mockResolvedValue({ data: "test" });

// 异步测试
test("异步操作", async () => {
const result = await asyncOperation();
expect(result).toBeTruthy();
});

知识测验

1/4正确 0

Jest 中 describe 和 test 的作用是什么?