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

使用web3.eth.getAccounts()获取Ganache测试账户时Mocha报错求助

解决Mocha测试中Ganache+Web3的"Error: Not supported"问题

针对你遇到的Mocha测试报错问题,可尝试以下几种解决方案:

  • 检查模块系统兼容性
    报错指向ESM的import(file)语句,大概率是项目混合了CommonJS和ESM模块。查看项目根目录的package.json,如果存在"type": "module"字段,要么将代码中的require改为import语法,要么删除该字段强制使用CommonJS模块系统。

  • 调整Mocha运行参数
    安装esm包来处理模块兼容:

    npm install esm --save-dev
    

    然后用以下命令运行测试:

    mocha -r esm
    

    或者尝试启用Node的实验性ESM支持:

    mocha --experimental-modules
    
  • 锁定课程兼容的依赖版本
    Stephen Grider课程中经过验证的版本组合能避免多数兼容性问题,执行以下命令重装依赖:

    npm uninstall web3 ganache mocha
    npm install web3@1.8.0 ganache@7.8.0 mocha@10.2.0 --save-dev
    
  • 优化代码异步逻辑
    将beforeEach中的then改为async/await,避免异步时序问题:

    const assert = require('assert');
    const ganache = require('ganache');
    const { Web3 } = require('web3');
    const web3 = new Web3(ganache.provider());
    
    beforeEach(async () => {
      const fetchedAccounts = await web3.eth.getAccounts();
      console.log(fetchedAccounts);
    });
    
    describe("Inbox", () => {
      it("deploys a contract", () => {});
    });
    
  • 显式配置Ganache Provider
    新版Ganache可能需要指定网络配置,尝试修改Provider初始化代码:

    const web3 = new Web3(ganache.provider({ network: "development" }));
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 13:32:05