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

更新react-horizontal-scrolling-menu至4.0.4后Jest测试报错求助

问题

使用create-react-app默认配置创建的React项目,此前使用react-horizontal-scrolling-menu@3.2.5时Jest测试运行正常。将版本升级到4.0.4后,执行npm run test或yarn run test时出现报错。

复现步骤:

  • 创建新React应用:npx create-react-app my-app
  • 安装最新版依赖:npm install react-horizontal-scrolling-menu@latest
  • 执行测试命令:npm run test 或 yarn run test
  • 报错触发
解决方案

1. 配置Jest转译目标包

新版本react-horizontal-scrolling-menu可能使用了未转译的ES模块语法,而create-react-app默认不会转译node_modules中的包。需要修改Jest配置,让其转译该包:
在项目根目录的package.json中添加Jest配置:

"jest": {
  "transformIgnorePatterns": [
    "node_modules/(?!react-horizontal-scrolling-menu)/"
  ]
}

如果项目使用独立的jest.config.js文件,添加同样的配置项即可。

2. 降级回兼容版本

如果不需要新版本的特性,直接降级到之前能正常运行的版本:

npm install react-horizontal-scrolling-menu@3.2.5
# 或使用yarn
yarn add react-horizontal-scrolling-menu@3.2.5

3. 补充测试环境缺失的Polyfill

若报错是因为新版本依赖了浏览器环境的API(如IntersectionObserver),而Jest的Node.js测试环境没有提供这些API,可以在src/setupTests.js中添加模拟或polyfill:

// 模拟IntersectionObserver示例
global.IntersectionObserver = class IntersectionObserver {
  constructor(callback) {
    this.callback = callback;
  }
  observe() {}
  unobserve() {}
  disconnect() {}
};

根据具体报错信息补充对应的polyfill或模拟实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 02:37:11