jest.fn() 是 jest 提供的基础 mock 函数,可记录调用信息、自定义返回值/实现,并支持链式断言;调用记录独立,jest 默认自动重置。

jest.fn() 是 Jest 提供的最基础的 Mock 函数创建方式,它返回一个可被调用、可断言、可配置行为的函数,并自动记录每次调用的参数、返回值、调用次数等信息。
1. 创建并验证基本调用记录
直接调用 jest.fn() 就能得到一个空函数,它默认返回 undefined,但会默默记录所有调用细节:
const mockFn = jest.fn();
mockFn('a', 1);
mockFn('b', 2, true);
console.log(mockFn.mock.calls); // [['a', 1], ['b', 2, true]]
console.log(mockFn.mock.results); // [{ type: 'return', value: undefined }, { type: 'return', value: undefined }]
console.log(mockFn.mock.callCount); // 2
2. 控制返回值或抛出错误
可通过 mockReturnValue、mockReturnValueOnce 或 mockImplementation 等方法定制行为:
- mockReturnValue(42):后续所有调用都返回 42
- mockReturnValueOnce('first').mockReturnValueOnce('second'):前两次分别返回指定值,之后为 undefined
- mockImplementation(() => 'custom logic'):完全自定义执行逻辑(支持异步)
- mockImplementationOnce(() => Promise.resolve('done')):仅第一次按此实现
3. 常用断言写法(在 test 中)
Jest 提供了链式断言方法,让验证更直观:
test('mock function is called with correct args', () => {
const fn = jest.fn();
fn('hello', 123);
expect(fn).toHaveBeenCalledTimes(1);
expect(fn).toHaveBeenCalledWith('hello', 123);
expect(fn).toHaveBeenNthCalledWith(1, 'hello', 123);
expect(fn).toHaveReturnedWith(undefined);
});
4. 注意事项
mock 函数的调用记录是独立的,每次重新赋值 jest.fn() 都会重置状态;若需复用或重置,可用 mockFn.mockClear() 清空记录,或 mockFn.mockReset() 同时清空记录和实现逻辑。测试结束后通常无需手动清理,Jest 会在每个 test 后自动重置(取决于配置,如 clearMocks: true)。











