01
快速上手
基础测试
用 test/expect 编写断言。
jest
test("adds numbers", () => {
expect(1 + 2).toBe(3);
});Describe
describe 把相关测试分组。
jest
describe("Math", () => {
test("add", () => expect(1+1).toBe(2));
test("sub", () => expect(2-1).toBe(1));
});匹配器
常用匹配器。
jest
expect(value).toBe(other);
expect(arr).toContain(item);
expect(obj).toEqual({a: 1});
expect(fn).toThrow();
expect(promise).resolves.toBe(42);02
核心特性
Mock
jest.fn() 创建 mock 函数。
jest
const mockFn = jest.fn();
mockFn.mockReturnValue(42);
mockFn();
expect(mockFn).toHaveBeenCalled();异步测试
异步测试使用 async/await。
jest
test("async", async () => {
const data = await fetchData();
expect(data).toBe("ok");
});Before/After 钩子
准备与清理的钩子函数。
jest
beforeEach(() => setup());
afterEach(() => cleanup());
afterAll(() => db.close());快照
对 UI 组件做快照测试。
jest
expect(component).toMatchSnapshot();这篇内容对您有帮助吗?