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

Jest测试Web3.js外部调用报错:createKeccakHash is not a function

解决Jest测试Web3.js时的两个关键问题

一、当前错误:TypeError: createKeccakHash is not a function

这个错误源于Web3.js依赖的哈希函数包未正确安装或Jest环境未兼容处理,解决步骤如下:

  1. 确保依赖安装完整
    运行以下命令安装缺失的依赖包:

    npm install keccak web3 --save-dev
    # 或使用yarn
    yarn add keccak web3 --dev
    
  2. 配置Jest兼容Web3.js的模块
    在jest.config.js中添加transformIgnorePatterns,避免Jest转译Web3相关的未转译模块:

    module.exports = {
      transformIgnorePatterns: [
        '/node_modules/(?!web3|ethereum-cryptography|keccak)/'
      ]
    };
    
  3. 全局注入哈希函数(可选)
    如果上述配置仍未解决问题,可在测试文件顶部或Jest的setup文件中全局注入createKeccakHash:

    import createKeccakHash from 'keccak';
    global.createKeccakHash = createKeccakHash;
    

二、历史错误:can not console response after the end of test

该问题是由于测试已结束,但异步操作仍在执行,导致日志输出脱离测试上下文。调整测试逻辑即可解决:

  1. 严格包裹所有异步操作
    使用waitFor确保所有异步调用(如bal())在测试生命周期内完成,避免测试函数提前结束。

  2. 优化后的测试代码示例

    describe("Deployment", function () {
      it("Should set the right unlockTime", async () => {
        try {
          const { result, rerender } = renderHook(() => useAccounts(), { wrapper: MockApp });
          
          // 等待hook返回值就绪
          await waitFor(() => expect(result.current).toBeDefined());
          
          const accounts = await result.current;
          console.log("Accounts data:", accounts);
          
          rerender();
          
          // 等待balance请求完成并获取结果
          const balance = await waitFor(async () => {
            const balResult = await accounts.bal();
            console.log("Fetched balance:", balResult);
            return balResult;
          });
          
          console.log("Final balance:", balance);
        } catch (error) {
          console.error("Test failed:", error);
        }
      });
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 11:01:15