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

React+TypeScript引入Swiper后Jest文件解析失败求助

解决React+TS项目中Swiper导致的Jest解析失败问题

第一步:合并Jest配置,消除冲突

Jest配置分散在多个文件会导致优先级冲突,建议统一到jest.config.js,删除其他文件中的冗余Jest配置项。

修改后的jest.config.js

import type { Config } from '@jest/types';

const config: Config.InitialOptions = {
  verbose: true,
  transform: {
    '^.+\\.(ts|tsx)$': 'ts-jest',
    '^.+\\.(js|jsx)$': 'babel-jest',
    '^.+\\.css$': 'jest-transform-css'
  },
  transformIgnorePatterns: ['node_modules/(?!swiper|ssr-window|dom7/)'],
  moduleNameMapper: {
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      '<rootDir>/__mocks__/fileMock.js',
    'swiper/react': 'swiper/react/swiper-react.js',
    'swiper/css': 'swiper/swiper.min.css'
  },
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node']
};
export default config;

第二步:修复babel.config.js的错误配置

移除Babel配置中不属于它的Jest属性,修正路径转义问题,并替换适配TS的预设:

修改后的babel.config.js

module.exports = {
  presets: ['@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript'],
  plugins: [
    'babel-plugin-styled-components',
    '@babel/plugin-proposal-class-properties'
  ],
  moduleNameMapper: {
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      '<rootDir>/__mocks__/fileMock.js',
    '\\.(css|less)$': '<rootDir>/__mocks__/styleMock.js'
  }
};

第三步:清理package.json中的冗余配置

删除package.json里的"jest"配置块,以及外层的"transformIgnorePatterns",确保Jest仅读取jest.config.js的配置。

第四步:添加Swiper组件Mock(可选)

如果测试不需要真实渲染Swiper,可创建Mock文件避免转译问题:
在__mocks__/swiper/react.js中写入:

export const Swiper = ({ children }) => <div>{children}</div>;
export const SwiperSlide = ({ children }) => <div>{children}</div>;
// 按需导出你使用的其他Swiper组件

然后在jest.config.js的moduleNameMapper中追加:

'swiper/react': '<rootDir>/__mocks__/swiper/react.js'

验证修复

运行Jest测试命令,若仍有问题,检查是否安装了必要依赖:
执行npm install --save-dev @babel/preset-typescript补充TS适配预设。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 09:05:23