React Next.js项目RTL测试Swiper时出现SyntaxError求助
解决方案
1. 修正jest.config.js的transformIgnorePatterns配置
Jest默认会忽略node_modules里的模块转译,但Swiper是ES模块,得让Jest转译它和它的依赖。修改你的jest.config.js:
const nextJest = require('next/jest') const createJestConfig = nextJest({ dir: './', }) const customJestConfig = { moduleDirectories: ['node_modules', '<rootDir>/'], testEnvironment: 'jest-environment-jsdom', // 排除swiper及相关依赖,不让Jest忽略转译 transformIgnorePatterns: [ '/node_modules/(?!swiper|swiper/react|ssr-window|dom7)/', ], } module.exports = createJestConfig(customJestConfig)
2. 确保Babel配置支持ES模块转译
如果项目有babel.config.js,确认配置包含必要预设,保证能转译ES模块:
module.exports = { presets: [ 'next/babel', ['@babel/preset-env', { targets: { node: 'current' } }], ], }
3. 调整测试脚本(如果之前的配置不对)
检查package.json里的测试脚本,确保指向正确的Jest命令:
{ "scripts": { "test:rtl": "jest --watch" } }
4. 核对Swiper的导入方式
如果你用的是Swiper 8及以上版本,确保组件里的导入是ES模块格式:
import { Swiper, SwiperSlide } from 'swiper/react'; import 'swiper/css';
别导入CommonJS版本的文件。
5. 清除Jest缓存再测试
有时候缓存会导致新配置不生效,先清缓存再跑测试:
npx jest --clearCache
内容的提问来源于stack exchange,提问作者Subhasish Nath
相关产品推荐
相关产品推荐

