使用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
相关产品推荐
相关产品推荐

