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

组件测试报错:SyntaxError: Cannot use import statement outside a module

Jest测试中Axios导入报错:SyntaxError: Cannot use import statement outside a module

我在为组件编写渲染验证测试时遇到该错误,测试代码如下:

test('Should render the movie info', () => {
  renderWithContext(<MovieInfo movie={mockMovies[0]} />);
  expect(screen.getByText('Terrifier 2')).toBeInTheDocument();
});

运行测试时触发错误:

SyntaxError: Cannot use import statement outside a module

错误源自axios的导入语句:

> 2 | import axios from 'axios';
    | ^

当前jest.config.js配置:

const { compilerOptions } = require('./tsconfig.json');

const { pathsToModuleNameMapper } = require('ts-jest');
const { default: tsjPreset } = require('ts-jest');
module.exports = {
  transform: {
    ...tsjPreset.transform,
    '+\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2|pdf)$':
      'jest-transform-stub',
    '^.+\.ts?$': 'ts-jest',
  },
  moduleDirectories: ['src', 'node_modules'],
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),
  setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'],
  transformIgnorePatterns: ['node_modules/(?!(axios)/)'],
};

已安装依赖:ts-jest、@types/jest、jest-transform-stub


解决步骤

  1. 修正transformIgnorePatterns正则
    原配置的正则存在冗余语法,修改为:

    transformIgnorePatterns: ['node_modules/(?!axios)'],
    

    确保Jest不对axios模块跳过转换,因为axios采用ES模块语法,需要ts-jest处理。

  2. 修复transform中的文件后缀匹配正则
    原配置里'+\.(css|...)'的正则写法错误,+无匹配意义,改为:

    '\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2|pdf)$': 'jest-transform-stub',
    
  3. 调整transform规则,覆盖所有需要转换的文件
    移除可能冲突的tsjPreset.transform,明确指定ts-jest处理TS/JS文件:

    transform: {
      '^.+\\.(ts|tsx|js|jsx)$': 'ts-jest',
      '\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2|pdf)$': 'jest-transform-stub',
    },
    
  4. 检查tsconfig.json模块配置
    确保compilerOptions.module设置为CommonJS(Jest默认兼容),如果使用ESNext,需在jest.config.js中添加:

    module: 'ESNext',
    extensionsToTreatAsEsm: ['.ts', '.tsx'],
    
  5. 兜底方案:Mock axios
    若上述方法仍无效,直接在测试文件顶部Mock axios,避免实际导入引发的模块问题:

    jest.mock('axios', () => ({
      default: jest.fn(() => Promise.resolve({ data: {} })),
    }));
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 13:20:35