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

使用Jest-Cucumber+React Testing Library报错:ReferenceError: _react1 is not defined

解决React Testing Library + Jest-Cucumber 出现 ReferenceError: _react1 is not defined 的问题

可能的原因与修复方案

1. 移除手动包裹的act调用

React Testing Library的render方法已经自动在act上下文内执行,手动嵌套act会干扰React的内部状态管理,导致变量绑定异常。修改你的beforeEach逻辑:

beforeEach(() => {
  render(<LoginPage />);
});

2. 调整Jest的转译规则

确保Jest正确转译node_modules中的相关依赖,避免转译遗漏导致编译后变量未定义。在jest.config.js中更新配置:

module.exports = {
  transform: {
    '^.+\\.(ts|tsx)$': 'ts-jest',
    '^.+\\.(js|jsx)$': 'babel-jest',
  },
  transformIgnorePatterns: [
    '/node_modules/(?!@testing-library|jest-cucumber|@babel/runtime)'
  ],
};

3. 验证依赖版本兼容性

jest-cucumber与@testing-library/react、jest的版本不匹配可能引发此类编译错误。执行命令升级到稳定兼容版本:

npm update jest-cucumber @testing-library/react jest ts-jest

也可查看jest-cucumber官方文档确认其peerDependencies要求。

4. 检查TypeScript的JSX编译配置

确保tsconfig.json中的JSX编译选项正确,避免生成错误的React引用代码:

{
  "compilerOptions": {
    "jsx": "react-jsx", // 开发环境可使用react-jsxdev
    "module": "ESNext",
    "target": "ES2020"
  }
}

5. 确认Jest的模块扩展名配置

确保Jest识别你的测试文件扩展名(.tsx/.jsx),在jest.config.js中添加:

module.exports = {
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'],
};

验证步骤

  1. 先移除beforeEach中的act包裹,重新运行测试
  2. 若问题仍存在,检查Jest的transformIgnorePatterns配置
  3. 最后验证依赖版本和TypeScript配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 11:36:09