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

使用React Testing Library测试组件时出现语法错误求助

React Testing Library测试时SyntaxError问题解决

测试React组件时出现如下错误:

SyntaxError: C:\Users\H525043\ReactApp\uma\monorepo_ui\node_modules@testing-library\react\node_modules@types\react-dom\client.d.ts: Unexpected token (7:13)

// See https://github.com/facebook/react/blob/main/packages/react-dom/client.js to see how the exports are declared,
import React = require('react');
^
export interface HydrationOptions {

系统提示:若仅需模拟非JS模块(如二进制资源),可通过moduleNameMapper配置选项进行存根。

解决方案:

  • 配置Jest处理TypeScript语法
    错误源于Jest无法解析TypeScript的import = require()语法,需在Jest配置文件(jest.config.js或package.json的jest字段)中添加transform配置,用ts-jest转换TypeScript文件:

    module.exports = {
      transform: {
        '^.+\\.tsx?$': 'ts-jest',
      },
      moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
    };
    
  • 调整node_modules转换规则
    确保Jest能正确处理依赖中的类型文件,在配置中修改transformIgnorePatterns,排除需要转换的依赖路径:

    module.exports = {
      transformIgnorePatterns: [
        'node_modules/(?!@testing-library/react|@types/react-dom)',
      ],
    };
    
  • 更新相关依赖版本
    版本不兼容可能导致该问题,尝试更新依赖到兼容版本:

    npm update @types/react-dom @testing-library/react jest ts-jest
    
  • 配置非JS模块存根
    若项目包含图片、样式等非JS模块,按提示配置moduleNameMapper:

    module.exports = {
      moduleNameMapper: {
        '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
          '<rootDir>/__mocks__/fileMock.js',
        '\\.(css|less)$': '<rootDir>/__mocks__/styleMock.js',
      },
    };
    

    对应mock文件示例(styleMock.js):

    module.exports = {};
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 23:12:25