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

使用Jest快照测试时引入SwiperJs遇Unexpected token错误

解决Jest测试含Swiper的React组件时的SyntaxError: Unexpected token 'export'问题

这个错误是因为Swiper及其依赖使用了ES模块语法,而Jest默认不会转译node_modules中的包,导致无法解析export语句。以下是具体解决步骤:

1. 配置Jest转译Swiper相关包

在你的Jest配置文件(jest.config.js)或者package.json的jest字段中,添加transformIgnorePatterns,指定转译Swiper及其依赖:

// jest.config.js
module.exports = {
  // 其他配置...
  transformIgnorePatterns: [
    'node_modules/(?!swiper|swiper-react|ssr-window|dom7)'
  ]
};

如果是在package.json中配置:

{
  "jest": {
    "transformIgnorePatterns": [
      "node_modules/(?!swiper|swiper-react|ssr-window|dom7)"
    ]
  }
}

2. 确保Babel配置正确

检查你的babel.config.js(或.babelrc)是否包含必要的预设:

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

3. 针对Create React App项目的特殊处理

如果你用的是Create React App,默认无法直接修改Jest配置,需要借助@craco/craco覆盖配置:

  • 安装依赖:yarn add --dev @craco/craco
  • 在项目根目录创建craco.config.js:
module.exports = {
  jest: {
    configure: {
      transformIgnorePatterns: [
        'node_modules/(?!swiper|swiper-react|ssr-window|dom7)'
      ]
    }
  }
};
  • 修改package.json中的脚本,将test命令改为craco test:
{
  "scripts": {
    "test": "craco test"
  }
}

完成以上配置后,重新运行Jest测试,即可正常生成包含Swiper组件的快照。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 04:55:23