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

React-Leaflet组件单元测试出现Unexpected token错误求助

解决Jest测试React-Leaflet组件时的"Unexpected token 'export'"错误

问题原因

Jest默认跳过node_modules目录下文件的转译,但react-leaflet输出的是ES模块语法(使用export关键字),Jest默认配置无法解析这类语法,因此抛出错误。

解决方案

方案1:修改Jest配置,转译react-leaflet相关依赖

在Jest配置文件(jest.config.js或package.json的jest字段)中,调整transformIgnorePatterns,让Jest对react-leaflet及其关联依赖进行转译:

示例 jest.config.js:

module.exports = {
  transform: {
    '^.+\\.(ts|tsx|js|jsx)$': 'babel-jest',
  },
  transformIgnorePatterns: [
    'node_modules/(?!(react-leaflet|leaflet|@react-leaflet)/)'
  ],
  // 保留其他原有配置
};

如果在package.json中配置:

{
  "jest": {
    "transform": {
      "^.+\\.(ts|tsx|js|jsx)$": "babel-jest"
    },
    "transformIgnorePatterns": [
      "node_modules/(?!(react-leaflet|leaflet|@react-leaflet)/)"
    ]
  }
}

方案2:Mock React-Leaflet组件(无需真实渲染地图)

若测试仅需验证组件结构,不需要真实渲染Leaflet地图,可直接mockreact-leaflet核心组件:

在测试文件顶部添加mock代码:

import { render } from '@testing-library/react';
import LeafletMap from '../_LeafletMap';

jest.mock('react-leaflet', () => ({
  MapContainer: ({ children }) => <div data-testid="map-container">{children}</div>,
  TileLayer: () => <div data-testid="tile-layer" />,
  GeoJSON: () => <div data-testid="geojson" />
}));

describe('Leaflet Map Component', () => {
  it('should render', () => {
    render(<LeafletMap />);
    // 可添加断言验证mock组件渲染状态
    // expect(screen.getByTestId('map-container')).toBeInTheDocument();
  });
});

方案3:检查Babel配置支持ES模块

确认你的.babelrc或babel.config.js配置了正确预设,以处理ES模块语法:

示例 babel.config.js:

module.exports = {
  presets: [
    '@babel/preset-env',
    '@babel/preset-react',
    '@babel/preset-typescript' // 若使用TypeScript则添加
  ]
};

内容的提问来源于stack exchange,提问作者Sajeeb M Ahamed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 02:15:01