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

Vue项目中使用Wagmi与Web3Modal时Jest测试报模块导入语法错误

解决Jest测试@wagmi/core和@web3modal/wagmi/vue的模块导入错误

问题原因

@wagmi/core和@web3modal/wagmi/vue发布的是ES模块格式,Jest默认会忽略node_modules目录下的文件转译,导致CommonJS运行环境无法识别ES模块的import语法。你现有配置的transformIgnorePatterns存在空格语法错误,且未覆盖wagmi依赖的其他ES模块包,导致转译规则失效。

修正方案

1. 修复transformIgnorePatterns配置

移除@web3modal/wagmi/vue前的多余空格,同时将wagmi的核心依赖(如viem、@web3modal/core)加入转译白名单,确保所有相关ES模块都能被转译:

transformIgnorePatterns: [
  '<rootDir>/node_modules/(?!(@wagmi/core|@web3modal/wagmi|viem|@web3modal/core))'
],

2. 调整testEnvironmentOptions的模块加载优先级

当前配置的customExportConditions优先加载node环境模块,但wagmi相关包未提供CommonJS版本,改为优先加载浏览器/ES模块版本:

testEnvironmentOptions: {
  customExportConditions: ['browser', 'module'],
},

3. 确保Babel配置支持ES模块转译

在项目的babel.config.js中添加兼容配置,确保ES模块能被转译为CommonJS:

module.exports = {
  presets: [
    ['@babel/preset-env', { targets: { node: 'current' } }],
    '@babel/preset-typescript'
  ]
};

4. 同步jest-environment-jsdom版本

确保jest-environment-jsdom版本与Jest主版本(v29.6.2)一致,避免环境兼容问题:

npm install jest-environment-jsdom@29.6.2 --save-dev

完整修正后的jest.config.js

module.exports = {
  preset: 'ts-jest/presets/js-with-babel',
  testEnvironment: 'jsdom',
  testEnvironmentOptions: {
    customExportConditions: ['browser', 'module'],
  },
  coverageThreshold: {
    global: {
      branches: 55,
      functions: 64,
      lines: 70,
      statements: 70,
    },
  },
  testPathIgnorePatterns: ['/.deploy', '/build'],
  transformIgnorePatterns: [
    '<rootDir>/node_modules/(?!(@wagmi/core|@web3modal/wagmi|viem|@web3modal/core))'
  ],
  transform: {
    '^.+\\.vue$': '@vue/vue3-jest',
    '^.+\\.ts$': 'ts-jest',
    '^.+\\.js$': 'babel-jest',
    '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
    '^.+\\.svg$': '<rootDir>/tests/unit/svgTransform.js',
  },
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(js|ts)$',
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
    '^.+/(.*\\.svg)': '<rootDir>/src/assets/images/$1',
    'moment/dist/locale/(.*)': 'moment/locale/$1',
  },
  moduleFileExtensions: ['vue', 'js', 'ts', 'json', 'scss', 'svg'],
  setupFiles: ['./jest.polyfills.js'],
  setupFilesAfterEnv: ['<rootDir>/tests/unit/jest_setup.ts'],
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 22:59:59