Jest 是一个由 Facebook 维护的令人愉悦的 JavaScript 测试框架。它广泛用于现代 JavaScript 和 Node.js 应用中的单元测试、集成测试,甚至端到端测试。Jest 提供了一套强大的功能,包括内置测试运行器、断言库、模拟工具、快照测试和测试覆盖率报告。
本指南针对 Jest v20,提供简洁而实用的使用概览。
describe():用于将相关测试用例分组到测试套件中。test() / it():定义单个测试用例。it() 只是 test() 的 BDD 风格别名。expect():断言库,检查值是否符合预期。beforeEach() / afterEach():在套件中的每个测试之前或之后运行代码。beforeAll() / afterAll():在所有测试之前或之后运行一次设置/清理代码。.only / .skip:聚焦或忽略特定测试/套件。setTimeout() 和 setInterval()。async/await 的测试。describe('My work', () => {
test('works', () => {
expect(2).toEqual(2);
});
});
🔄 it() 是 test() 的别名。
用于设置/清理例程:
beforeEach(() => { ... });
afterEach(() => { ... });
beforeAll(() => { ... });
afterAll(() => { ... });
聚焦测试:
describe.only(...);
it.only(...); // 或 fit()
跳过测试:
describe.skip(...);
it.skip(...); // 或 xit()
| 标志 | 描述 |
|---|---|
--coverage |
显示测试覆盖率摘要 |
--detectOpenHandles |
检测未关闭的句柄(例如套接字) |
--runInBand |
串行运行测试(对 CI 有用) |
expect(value).not.toBe(value);
expect(value).toEqual(value);
expect(value).toBeTruthy();
注意:
toEqual执行深度相等。
expect(value).toMatchSnapshot();
expect(value).toMatchInlineSnapshot();
内联快照需要 Prettier。
expect(fn).toThrow(error);
expect(fn).toThrowErrorMatchingSnapshot();
expect(value).toBeFalsy();
expect(value).toBeNull();
expect(value).toBeTruthy();
expect(value).toBeUndefined();
expect(value).toBeDefined();
expect(value).toBeCloseTo(number, digits);
expect(value).toBeGreaterThan(number);
expect(value).toBeLessThanOrEqual(number);
expect(value).toBeInstanceOf(Class);
expect(value).toMatchObject(obj);
expect(value).toHaveProperty('key', value);
expect(value).toContain(item);
expect(value).toHaveLength(number);
expect(value).toMatch(/pattern/);
expect.extend(customMatchers);
expect.any(Constructor);
expect.assertions(1);
it('renders correctly', () => {
const output = something();
expect(output).toMatchSnapshot();
});
对于 React 组件:
import renderer from 'react-test-renderer';
it('matches snapshot', () => {
const tree = renderer.create(<Component />).toJSON();
expect(tree).toMatchSnapshot();
});
jest.useFakeTimers();
it('delays call', () => {
jest.runOnlyPendingTimers();
jest.runAllTimers();
});
📖 参见:定时器模拟
const fn = jest.fn();
const squared = jest.fn((n) => n * n);
expect(fn).toHaveBeenCalled();
expect(fn).toHaveBeenCalledTimes(2);
expect(fn).toHaveBeenCalledWith(arg1, arg2);
expect(fn).toHaveBeenCalledWith(expect.any(String));
expect(fn).toHaveBeenCalledWith(expect.arrayContaining([1, 2]));
const MyClass = jest.fn();
const a = new MyClass();
const b = new MyClass();
MyClass.mock.instances; // [a, b]
fn.mock.calls.length;
fn.mock.calls[0][0];
jest.fn().mockReturnValue('hello');
jest.fn().mockReturnValueOnce('hi');
const fn = jest
.fn()
.mockImplementationOnce(() => 1)
.mockImplementationOnce(() => 2);
这份综合指南帮助你开始使用 Jest 测试或像专业人士一样使用它。它与 React Testing Library 完美配合,实现以用户为中心的测试工作流。