使用Enzyme mount挂载组件测试时遭遇元素类型无效错误求助
React组件mount测试报错解决指南
错误信息
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports
测试代码
import React from "react"; import {configure} from "enzyme"; import mount from "enzyme/mount" import Adapter from "enzyme-adapter-react-16"; import { IntlProvider } from "react-intl"; import { BrowserRouter } from "react-router-dom"; import enTranslations from "../../translations/en.json"; import CharacteristicTable from "./characteristicTable"; describe("<CharacteristicTable /> component", () => { let wrapper; beforeEach(() => { wrapper = mount( <IntlProvider locale="en" messages={enTranslations}> <CharacteristicTable {...props} /> </IntlProvider> ); }); it("Should render without exploding", () => { expect(wrapper.length).toEqual(1); }); }
环境版本
- react: 16.17.0
- npm: 8.15.0
- enzyme: ^3.11.0
- enzyme-adapter-react-16: ^1.15.6
- jest: ^29.3.1
- jest-cli: ^29.3.1
- jest-junit: ^14.0.0
- jest-react-hooks-shallow: ^1.5.1
解决步骤
1. 核对组件导入导出匹配
打开characteristicTable.js文件,确认组件导出方式:
- 若组件是默认导出:
export default CharacteristicTable,当前import CharacteristicTable from "./characteristicTable"写法正确; - 若组件是命名导出:
export const CharacteristicTable = ...,需将导入改为import { CharacteristicTable } from "./characteristicTable"; - 确保组件文件未遗漏导出语句。
2. 补全Enzyme适配器配置
测试代码仅导入了配置工具但未执行配置,这会导致Enzyme无法适配React 16,在文件开头添加配置代码:
configure({ adapter: new Adapter() });
3. 定义测试用props
测试代码中使用了{...props}但未声明该变量,需在describe块前或内部定义符合组件要求的props对象,示例:
const props = { // 填入组件所需属性,比如data: []等 };
4. 验证依赖版本兼容性
jest@29与enzyme@3.11.0存在部分兼容性问题,若上述步骤无效,可尝试将jest版本降级到26.x或27.x,或升级enzyme至最新兼容版本。
内容的提问来源于stack exchange,提问作者Koushik J
相关产品推荐
相关产品推荐

