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

Next.js中Jest兼容第三方ESM npm包的两难问题求助

解决Jest兼容ESM包(wagmi)并保留Mock功能的方案

针对你在t3-stack v6.2.1、Next.js v12.3.1、Jest v29.3.1环境下遇到的两难问题,以下是两个可行的解决方案:

方案一:在CommonJS模式下转译ESM依赖(推荐)

此方案无需切换Jest的ESM模式,通过调整转译配置让Jest处理wagmi这类ESM包,同时保留完整的Mock能力:

  1. 更新jest.config.js配置
    修改transformIgnorePatterns,将wagmi及其核心依赖从忽略转译列表中移除,确保Jest转译这些包:

    const nextJest = require('next/jest')
    
    const createJestConfig = nextJest({
      dir: './',
    })
    
    const customJestConfig = {
      moduleDirectories: ['node_modules', '<rootDir>/'],
      testEnvironment: 'jest-environment-jsdom',
      // 关键:移除wagmi、viem等依赖的转译忽略
      transformIgnorePatterns: [
        '/node_modules/(?!wagmi|viem|@wagmi/core|@tanstack/react-query)/',
      ],
      // 保留Next.js默认的转译配置
      transform: {
        '^.+\\.(js|jsx|ts|tsx)$': ['babel-jest', { presets: ['next/babel'] }],
      },
    }
    
    module.exports = createJestConfig(customJestConfig)
    
  2. 确认babel配置支持ESM转译
    项目根目录的babel.config.js需包含Next.js预设:

    module.exports = {
      presets: ['next/babel'],
    }
    

    配置完成后,Jest会自动将wagmi的ESM语法转译为CommonJS,既解决导入报错,又能正常使用jest.mockMock React Hooks。

方案二:在ESM模式下修复Mock功能

如果必须使用Jest的ESM模式,需调整Mock写法适配ES模块规范:

  1. 改用ESM格式的jest配置文件
    将jest.config.js重命名为jest.config.mjs,配置如下:

    import nextJest from 'next/jest.js'
    
    const createJestConfig = nextJest({
      dir: './',
    })
    
    const customJestConfig = {
      moduleDirectories: ['node_modules', '<rootDir>/'],
      testEnvironment: 'jest-environment-jsdom',
      extensionsToTreatAsEsm: ['.ts', '.tsx'],
      moduleNameMapper: {
        '^(\\.{1,2}/.*)\\.js$': '$1',
      },
    }
    
    export default createJestConfig(customJestConfig)
    
  2. 使用Jest的ESM Mock API
    测试文件中需用jest.unstable_mockModule替代jest.mock,并通过动态导入获取模块:

    // 先Mock wagmi模块
    jest.unstable_mockModule('wagmi', () => ({
      useAccount: jest.fn(() => ({
        address: '0x123',
        isConnected: true,
      })),
    }))
    
    // 动态导入被测试组件和wagmi
    const { useAccount } = await import('wagmi')
    const { default: MyComponent } = await import('./MyComponent')
    
    describe('MyComponent', () => {
      it('renders connected account address', () => {
        render(<MyComponent />)
        expect(screen.getByText('0x123')).toBeInTheDocument()
      })
    })
    
  3. 运行测试命令
    保持使用以下命令启动测试:

    NODE_OPTIONS=--experimental-vm-modules jest
    

注意:方案一的兼容性更好,Next.js v12的Jest集成在CommonJS模式下更成熟,Mock功能更稳定,优先推荐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 22:55:17