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

使用Testing-Library/React与Jest时遇"Cannot use import..."错误如何解决?

解决Jest报错"Cannot use import statement outside a module"(@react-hook/debounce相关)

问题场景

运行React测试时,Jest抛出如下错误:

SyntaxError: Cannot use import statement outside a module

错误根源是依赖包@react-hook/debounce采用ESM语法,但Jest默认不会转换node_modules目录下的文件,导致无法解析该包中的import语句。

现有配置

package.json 开发依赖(关键部分)

"devDependencies": {
  "@babel/core": "^7.21.4",
  "@testing-library/react": "^14.0.0",
  "babel-jest": "29.5.0",
  "babel-preset-react-app": "^10.0.1",
  // 其他依赖...
}

Jest配置文件

module.exports = {
  roots: ['<rootDir>'],
  testRegex: './test/.*.(spec|test)\\.(js|jsx|ts|tsx)$',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'json', 'jsx'],
  moduleNameMapper: {
      '\\.svg': '<rootDir>/__mocks__/fileMock.js',
      '~/(.*)': '<rootDir>/$1',
      'lodash-es': 'lodash',
      '@emotion/core': '@emotion/react',
  },
  testPathIgnorePatterns: ['<rootDir>[/\\\\](node_modules|.next)[/\\\\]'],
  transformIgnorePatterns: ['[/\\\\]node_modules[/\\\\].+\\.(ts|tsx)$'],
  transform: {
      '^.+\\.(ts|tsx)$': 'babel-jest',
      '\\.graphql$': ['graphql-let/jestTransformer', { subsequentTransformer: 'babel-jest' }],
      '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
  },
  // 其他配置...
}

解决方案

修改Jest配置中的transformIgnorePatterns,将@react-hook/debounce从忽略转换的规则中排除,让Jest对该包进行Babel转换:

transformIgnorePatterns: [
  '[/\\\\]node_modules[/\\\\](?!@react-hook/debounce).+\\.(ts|tsx|js|jsx)$'
],

说明

  • (?!@react-hook/debounce)是正则中的负向预查,表示不匹配以@react-hook/debounce开头的路径
  • 扩展匹配的文件后缀为ts|tsx|js|jsx,确保该包下的所有JS/TS文件都会被Babel处理
  • 依赖已有的babel-jest和babel-preset-react-app,它们会自动将ESM语法转换为Jest可识别的CommonJS语法

修改完成后重新运行测试,即可解决该报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 15:23:11