为何beforeAll设置jest.fn()的mockReturnValue调用返回undefined,beforeEach正常?
Jest中beforeAll设置mock返回值无效,beforeEach却正常的原因
问题场景
我创建了一个jest.fn()函数,在beforeAll()中调用其mockReturnValue("hello")方法,测试用例中调用该函数时,console.log输出undefined;但将mockReturnValue("hello")的调用放在beforeEach()中时,调用该函数却能正常输出hello。
beforeAll设置的代码示例(输出undefined):
import App from "./App" describe("App", () => { const mock = jest.fn() beforeAll(() => { mock.mockReturnValue("hello") }) beforeEach(() => { }) afterEach(() => { }) afterAll(() => { }) it("should console.log the value 'hello'", () => { console.log(mock()) // undefined }) })
beforeEach设置的代码示例(输出hello):
import App from "./App" describe("App", () => { const mock = jest.fn() beforeAll(() => { }) beforeEach(() => { mock.mockReturnValue("hello") }) afterEach(() => { }) afterAll(() => { }) it("should console.log the value 'hello'", () => { console.log(mock()) // hello }) })
原因分析
核心问题出在Jest的resetMocks配置(多数项目会开启这个配置):
- 当
resetMocks设为true时,Jest会在每个测试用例执行前自动重置所有mock的实现与状态,把mock恢复成初始的jest.fn()状态(没有预设返回值)。 - Jest的执行顺序是:
beforeAll→ 触发resetMocks清空mock设置 →beforeEach→ 测试用例。 - 所以
beforeAll里设置的返回值会被resetMocks清空,测试用例调用时自然返回undefined;而beforeEach是在重置之后执行,设置的返回值不会被覆盖,因此能正常生效。
解决方法
有两种可行方案:
- 关闭resetMocks配置:如果你的mock返回值在所有测试用例中一致,且不需要在测试间重置mock,可以在
jest.config.js中修改配置:
module.exports = { resetMocks: false, };
修改后beforeAll里的mock设置就不会被清空,测试用例能正常拿到预设返回值。
- 保持resetMocks开启(推荐):这个配置能避免测试用例之间的mock状态污染,是更规范的做法。此时只需把mock返回值的设置放在
beforeEach中,确保每次测试前都重新初始化mock状态即可。
内容的提问来源于stack exchange,提问作者Austin Stephens
相关产品推荐
相关产品推荐

