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

在Jest中导入libsodium-wrappers抛出“Cannot read properties of undefined (reading 'sodium')”错误

解决Jest环境中导入libsodium-wrappers的sodium未定义错误

这个错误的核心原因是:libsodium-wrappers依赖底层的libsodium库提供全局sodium对象,但Jest的模块处理逻辑导致该对象未被正确初始化,进而出现Cannot read properties of undefined (reading 'sodium')报错。

以下是几种可行的解决方法:

  • 确保同时安装依赖库
    先确认项目中同时安装了libsodium-wrappers和底层的libsodium:

    npm install libsodium-wrappers libsodium --save-dev
    
  • 修改导入与初始化逻辑
    替换原有的直接导入代码,改为显式加载底层库并等待初始化完成:

    import sodium from 'libsodium-wrappers';
    import 'libsodium';
    
    // 在所有测试执行前完成初始化
    beforeAll(async () => {
      await sodium.ready;
    });
    
  • 配置Jest的模块解析路径
    如果上述方法无效,在jest.config.js中指定libsodium-wrappers的正确模块路径:

    module.exports = {
      moduleNameMapper: {
        'libsodium-wrappers': '<rootDir>/node_modules/libsodium-wrappers/dist/modules/libsodium-wrappers.js'
      }
    };
    
  • 使用动态导入方式
    另一种兼容方案是通过动态导入并等待初始化:

    let sodium;
    
    beforeAll(async () => {
      sodium = await import('libsodium-wrappers');
      await sodium.ready;
    });
    

内容的提问来源于stack exchange,提问作者Some Guy Trying To Do Math

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 18:48:23