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

Mocha运行测试报需使用new关键字实例化错误

Mocha运行Web3相关测试报「需使用new关键字实例化」错误解决

错误复现条件

  • 已安装依赖:执行npm install --save-dev mocha安装Mocha,测试文件引入assert、ganache-cli、web3三个依赖包
  • package.json测试脚本配置如下:
"scripts": {
  "test": "mocha"
}
  • 测试文件代码:
const assert = require('assert');
const ganache = require('ganache-cli');
const Web3 = require('web3');

const web3 = Web3(ganache.provider());

class Car{
    park(){
      return 'stopped!';  
    }
    drive(){
        return 'vroom';
    }
}

describe('Car', () => {
    it('Can be', () => {
        const car = new Car();
        assert.equal(car.park(), 'stopped!');
    })
})
  • 执行npm run test命令后抛出错误:
Error: You need to instantiate using the "new" keyword.

错误堆栈定位到测试文件第5行的Web3初始化语句。

错误原因

该错误和Mocha测试框架本身无关。Web3 1.0及以上版本的构造函数强制要求使用new关键字完成实例化,直接以普通函数形式调用Web3()就会触发该报错。

修复方法

修改Web3实例化语句,补充new关键字:

// 错误写法
// const web3 = Web3(ganache.provider());

// 正确写法
const web3 = new Web3(ganache.provider());

修改后重新执行npm run test,测试即可正常运行通过。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 02:45:49