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

Jest测试React组件导入Siwe模块时出现TypeError问题求助

Jest测试导入Siwe的React组件时出现Cannot read properties of undefined (reading 'utf16le')错误的解决方法

问题背景

测试导入SiweMessage的React组件时,Jest抛出TypeError: Cannot read properties of undefined (reading 'utf16le')错误,移除Siwe导入后测试可正常运行,错误溯源到apg-js模块的解码逻辑。

原因分析

Siwe依赖的@spruceid/siwe-parser使用了apg-js库,而apg-js依赖Node.js的Buffer API,Jest默认的jsdom测试环境不提供完整的Node.js API支持;同时你的Jest配置存在两处问题:

  • transformIgnorePatterns包含语法错误,且未覆盖需要转译的siwe相关依赖模块
  • moduleNameMapper的映射键错误,导致apg-js模块的导入路径异常

解决方案

1. 修正Jest核心配置

更新jest.config.js,移除错误映射、修正转译规则,确保siwe相关依赖被babel-jest处理:

module.exports = {
  // 移除错误的moduleNameMapper映射
  transform: {
    "\\.[jt]sx?$": "babel-jest",
  },
  testEnvironment: "jsdom",
  // 修正语法错误,添加需要转译的依赖模块
  transformIgnorePatterns: [
    'node_modules/(?!(@wagmi|siwe|@spruceid/siwe-parser|apg-js)/)'
  ],
  // 可选:指定初始化文件用于补全环境API
  setupFiles: ['<rootDir>/jest.setup.js'],
};

2. 补全Buffer API支持(可选但推荐)

如果调整转译规则后仍报错,需要为jsdom环境添加Buffer polyfill:

  • 安装依赖包:
npm install buffer --save-dev
  • 在项目根目录创建jest.setup.js文件,添加以下内容:
import { Buffer } from 'buffer';
global.Buffer = Buffer;

3. 重新执行测试

完成配置修改后,重新运行测试命令,即可正常加载Siwe模块并执行测试逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 06:05:51