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

如何在Jest中Mock带innerText的Script标签修复组件测试报错?

在Jest中Mock依赖Script标签的解决方案

针对测试报错TypeError: Cannot read property 'someKey' of null,本质是测试环境中不存在id为element的script元素,导致info为null。以下两种方案可以解决:

方法一:Mock document.getElementById 模拟Script元素

由于SomeComponent在模块导入阶段就会执行获取元素的代码,需要在导入MyComponent前提前Mock浏览器的document方法:

// 先Mock document方法,再导入组件
beforeAll(() => {
  // 模拟目标script元素及JSON内容
  const mockScriptElement = {
    innerText: JSON.stringify({ someKey: true })
  };

  // 覆盖document.getElementById
  global.document.getElementById = jest.fn((id) => {
    return id === 'element' ? mockScriptElement : null;
  });
});

import MyComponent from '../components/MyComponent';
import { shallow } from 'enzyme';

describe('Tests for MyComponent', () => {
  it('should render without errors', () => {
    const wrapper = shallow(<MyComponent />);
    expect(wrapper).toExist();
    expect(wrapper.text()).toBe('Hey');
  });

  afterAll(() => {
    // 恢复原始方法,避免影响其他测试用例
    jest.restoreAllMocks();
  });
});

方法二:直接Mock SomeComponent 模块

如果只需要测试MyComponent的逻辑,无需关心SomeComponent内部对script的解析,可以直接Mock它的导出:

// 提前Mock SomeComponent的导出值
jest.mock('../components/SomeComponent', () => ({
  test: true
}));

import MyComponent from '../components/MyComponent';
import { shallow } from 'enzyme';

describe('Tests for MyComponent', () => {
  it('should render "Hey" when test is true', () => {
    const wrapper = shallow(<MyComponent />);
    expect(wrapper).toExist();
    expect(wrapper.text()).toBe('Hey');
  });

  it('should render "not Hey" when test is false', () => {
    // 重置模块缓存并重新Mock
    jest.resetModules();
    jest.mock('../components/SomeComponent', () => ({
      test: false
    }));
    const MyComponent = require('../components/MyComponent').default;
    
    const wrapper = shallow(<MyComponent />);
    expect(wrapper.text()).toBe('not Hey');
  });
});

注意事项

  • 方法一适合需要验证SomeComponent对script内容解析逻辑的场景,必须保证Mock操作在组件导入前执行。
  • 方法二更轻量,专注于测试MyComponent自身分支逻辑,无需模拟DOM元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 06:22:45