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

React Jest中Mock外部模块静态方法失效问题排查

问题原因及解决步骤

你的mock未生效主要有几个关键遗漏点,逐个修正即可:

1. Mock后未重新加载组件

Jest会缓存模块导入,若你在mock操作前就导入了MyComponent,它会直接使用原始的Authenticate模块。必须在执行jest.doMock之后,动态重新导入组件。

2. Mock的导出结构不匹配

你的组件通过import Authenticate from '/api/Authenticate'做了默认导入,所以mock时要确保默认导出的对象包含hasGroup静态方法,而非直接把hasGroup作为命名导出。

3. 修正语法错误

你的测试代码存在括号闭合问题(jest.doMock的回调函数末尾多了分号、describe未闭合),这会导致代码执行异常。


修改后的测试代码示例

describe('Has Group', () => {
  beforeEach(() => {
    // 重置模块缓存,避免跨测试的模块污染
    jest.resetModules();
  });

  it('renders "Has group" when hasGroup returns true', () => {
    // 1. 先mock目标模块
    jest.doMock('/api/Authenticate', () => ({
      __esModule: true,
      // 匹配组件的默认导入结构,导出包含hasGroup的对象
      default: {
        hasGroup: jest.fn(() => true)
      }
    }));

    // 2. 动态导入组件(必须在mock之后执行)
    const MyComponent = require('./MyComponent').default;
    const { render, toJson } = require('react-test-renderer'); // 假设使用react-test-renderer

    const wrapper = render(<MyComponent />);
    expect(toJson(wrapper)).toMatchSnapshot();
    // 额外验证mock方法被调用
    expect(require('/api/Authenticate').default.hasGroup).toHaveBeenCalled();
  });

  it('renders "No group" when hasGroup returns false', () => {
    jest.doMock('/api/Authenticate', () => ({
      __esModule: true,
      default: {
        hasGroup: jest.fn(() => false)
      }
    }));

    const MyComponent = require('./MyComponent').default;
    const { render, toJson } = require('react-test-renderer');

    const wrapper = render(<MyComponent />);
    expect(toJson(wrapper)).toMatchSnapshot();
  });
});

关键说明

  • 动态导入:使用require而非顶部静态导入,确保每次测试都加载mock后的模块。
  • 匹配导出结构:如果Authenticate是默认导出的类,mock的default应为包含静态方法的类或对象;如果是默认导出的对象,直接导出包含hasGroup的对象即可。
  • 重置模块缓存:jest.resetModules()确保每个测试用例的模块导入独立,避免之前的mock影响当前测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 12:22:43