React项目使用Jest测试报错:Cannot read property 'hasOwnProperty' of undefined
解决React Jest测试中
TypeError: Cannot read property 'hasOwnProperty' of undefined的问题 我之前也碰到过几乎一模一样的报错,大概率是依赖版本不兼容或者配置方式不当导致的,下面是我整理的几个修复方案,你可以一步步尝试:
1. 清理依赖冲突,统一核心包版本
首先要注意:react-scripts本身已经内置了Jest,你手动安装的jest@26.6.3很可能和内置版本产生冲突。建议先移除手动安装的Jest相关依赖:
npm uninstall jest jest-enzyme
另外,这个报错来自react-test-renderer,它的版本必须和react、react-dom完全一致。你可以打开package.json检查这三个包的版本,确保它们的版本号完全相同,之后重新安装依赖:
npm install
2. 规范Enzyme的配置位置
不要在单个测试文件里配置Enzyme,应该把配置放在src/setupTests.js文件中(create-react-app会自动执行这个文件的内容):
// src/setupTests.js import Enzyme from 'enzyme'; import EnzymeAdapter from 'enzyme-adapter-react-16'; Enzyme.configure({ adapter: new EnzymeAdapter() });
之后你的测试文件可以简化成:
import React from 'react'; import { shallow } from 'enzyme'; import YourComponent from './YourComponent'; // 替换成你的目标组件 test('should render without error', () => { const wrapper = shallow(<YourComponent />); expect(wrapper.exists()).toBe(true); });
3. 清理Jest缓存
有时候缓存会导致奇怪的版本兼容问题,执行下面的命令清空缓存:
npm test -- --clearCache
4. 检查React版本与适配器的兼容性
enzyme-adapter-react-16仅支持React 16.x版本,如果你的React是17及以上,需要替换成对应版本的适配器:
比如React 17的话:
npm uninstall enzyme-adapter-react-16 npm install @wojtekmaj/enzyme-adapter-react-17 --save-dev
然后更新setupTests.js里的适配器导入:
import EnzymeAdapter from '@wojtekmaj/enzyme-adapter-react-17';
按照上面的步骤试下来,应该能解决这个报错。
内容的提问来源于stack exchange,提问作者user12539769
相关产品推荐
相关产品推荐

