Jest测试报错:TypeError: Cannot redefine property: performance
Expo 48升级后Jest测试全部失败:TypeError: Cannot redefine property: performance
升级Expo从44版本到48版本后,所有Jest测试套件均无法运行,统一报错:
TypeError: Cannot redefine property: performance at Object.<anonymous> (node_modules/react-native/jest/setup.js:407:20)
解决方案
1. 前置脚本解锁performance属性
在项目根目录创建jest-pre-setup.js文件,内容如下:
Object.defineProperty(global, 'performance', { writable: true, value: global.performance || {}, });
修改Jest配置文件(如jest.config.js或package.json中的jest字段),将该脚本加入setupFiles:
// jest.config.js module.exports = { // 其他已有配置... setupFiles: ['./jest-pre-setup.js'], };
2. 对齐react-native与Expo版本
Expo 48对应react-native 0.71.x版本,确保依赖版本匹配,重新安装对应版本:
npm install react-native@0.71.8 # 或使用yarn yarn add react-native@0.71.8
3. 清除缓存并重装依赖
执行以下命令清理缓存并重新安装依赖:
# 清除Jest缓存 jest --clearCache # 清除npm缓存 npm cache clean --force # 重装依赖 rm -rf node_modules package-lock.json npm install
4. 排查自定义setup脚本冲突
如果项目已有自定义Jest setup文件,检查是否提前定义了performance属性,确保定义时设置writable: true,避免与react-native官方setup脚本冲突。
内容的提问来源于stack exchange,提问作者RenaissanceMan
相关产品推荐
相关产品推荐

