You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何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是在重置之后执行,设置的返回值不会被覆盖,因此能正常生效。

解决方法

有两种可行方案:

  1. 关闭resetMocks配置:如果你的mock返回值在所有测试用例中一致,且不需要在测试间重置mock,可以在jest.config.js中修改配置:
module.exports = {
  resetMocks: false,
};

修改后beforeAll里的mock设置就不会被清空,测试用例能正常拿到预设返回值。

  1. 保持resetMocks开启(推荐):这个配置能避免测试用例之间的mock状态污染,是更规范的做法。此时只需把mock返回值的设置放在beforeEach中,确保每次测试前都重新初始化mock状态即可。

内容的提问来源于stack exchange,提问作者Austin Stephens

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 19:01:14