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

Jest测试Ionic React组件时遇import语句不在模块内问题求助

Jest测试React+Ionic组件时出现“import statement outside a module”错误的解决方案

问题重现

测试导入Ionic模块的React组件时,在import { IonImg } from '@ionic/react';行触发错误:import statement outside a module,测试代码如下:

import { render, cleanup } from '@testing-library/react';
import { IonImg } from '@ionic/react';
import '@ionic/react-test-utils';

describe('<IonImg />', () => {
 afterEach(cleanup);

 it('renders an image with a valid src', () => {
    const { getByAltText } = render(
      <IonImg src="http://placehold.it/200x200" alt="Test image"></IonImg>
    );
    expect(getByAltText('Test image')).toHaveAttribute('src', 'http://placehold.it/200x200');
 });
}); 

已尝试Jest ES6模块实验特性、babel-jest预设转译,但问题未解决。

可行解决方案

1. 配置Jest转译Ionic依赖包

Jest默认不会转译node_modules中的包,但Ionic的React包采用ES模块格式,需要让babel-jest处理这些依赖:

在jest.config.js中添加以下配置:

module.exports = {
  transform: {
    '^.+\\.(js|jsx|ts|tsx)$': 'babel-jest',
  },
  // 排除node_modules中除Ionic相关包外的其他依赖,让babel转译它们
  transformIgnorePatterns: [
    'node_modules/(?!(@ionic/react|@ionic/react-router|@ionic/core)/)',
  ],
  testEnvironment: 'jsdom', // React测试需要jsdom环境
}

同时确保babel.config.js包含必要的预设:

module.exports = {
  presets: [
    '@babel/preset-env',
    '@babel/preset-react'
  ]
}

2. 确保版本兼容性

检查@ionic/react、@ionic/react-test-utils和Jest、babel相关依赖的版本是否匹配:

  • 确保@ionic/react和@ionic/react-test-utils版本完全一致
  • Jest版本建议使用28.x及以上,避免与ES模块支持的兼容性问题

3. 修正测试文件扩展名

确保测试文件使用.jsx或.tsx扩展名(而非.js),因为JSX语法需要babel的转译支持,扩展名错误可能导致Jest无法正确识别文件类型,进而触发模块导入错误。

4. 完善ES模块配置(若使用ES模块)

如果项目在package.json中设置了"type": "module",需要同步调整Jest配置:

  • 将jest.config.js重命名为jest.config.mjs
  • 在配置中添加ES模块相关设置:
export default {
  // 其他配置...
  extensionsToTreatAsEsm: ['.jsx', '.js'],
  moduleNameMapper: {
    '^(\\.{1,2}/.*)\\.js$': '$1',
  },
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 11:28:31