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

MonacoEditor与Jest、React Testing Library兼容问题及Mock求助

解决Jest测试@uiw/react-monacoeditor时的模块错误与Mock问题

问题梳理

测试依赖@uiw/react-monacoeditor的组件时,先后遇到三类错误:

  1. 初始模块找不到错误:

Cannot find module 'monaco-editor' from 'node_modules/@uiw/react-monacoeditor/lib/index.js'

  1. 添加moduleNameMapper配置后出现的新错误:

Error: Uncaught [TypeError: Cannot read properties of undefined (reading 'create')]

  1. 尝试Mock后触发的组件类型错误:

Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.

此前尝试的Mock代码:

jest.mock('@uiw/react-monacoeditor', ()=>({    
    MonacoEditor: ()=>null
}));

可行解决方案

1. 修正Mock写法,确保组件类型合法

你之前的Mock错误在于返回的MonacoEditor是null,这不是合法的React组件类型。根据组件的引入方式,选择对应的Mock方案:

若组件为默认导出

如果业务代码中是这样引入的:

import MonacoEditor from '@uiw/react-monacoeditor';

Mock代码应改为:

jest.mock('@uiw/react-monacoeditor', () => () => <div data-testid="mock-monaco-editor" />);

若组件为命名导出

如果业务代码中是命名引入:

import { MonacoEditor } from '@uiw/react-monacoeditor';

Mock代码调整为:

jest.mock('@uiw/react-monacoeditor', () => ({
  MonacoEditor: () => <div data-testid="mock-monaco-editor" />
}));

2. 移除无效的moduleNameMapper配置

之前添加的moduleNameMapper把monaco-editor映射到@uiw/react-monacoeditor的内部文件,会导致依赖逻辑混乱,直接删除该配置即可。

3. 完整测试示例

假设业务组件CodeEditor.jsx代码如下:

import { MonacoEditor } from '@uiw/react-monacoeditor';

export default function CodeEditor() {
  return <MonacoEditor value="console.log('test')" />;
}

对应的测试文件CodeEditor.test.jsx可编写为:

import { render } from '@testing-library/react';
import CodeEditor from './CodeEditor';

jest.mock('@uiw/react-monacoeditor', () => ({
  MonacoEditor: () => <div data-testid="mock-monaco" />
}));

test('正常渲染Mock的MonacoEditor组件', () => {
  const { getByTestId } = render(<CodeEditor />);
  expect(getByTestId('mock-monaco')).toBeInTheDocument();
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 12:57:11