Home > Mobile >  Mocha: You need to instantiate using the "new" keyword
Mocha: You need to instantiate using the "new" keyword

Time:07-11

I am just exploring mocha and I am facing a strange error. I have a not project and want to write some tests.

I have installed the node

npm install --save-dev mocha

My code is:

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!');
    })
})

I have also updated the Script element in the package.json

  "scripts": {
    "test": "mocha"
  },

When I run the test using the command:

npm run test

I am getting the following Error:

Error: You need to instantiate using the "new" keyword.

Stack Trace:

> [email protected] test
> mocha
 

 Error: You need to instantiate using the "new" keyword.
    at Object.packageInit (/Users/username/Blockchain/BlockchainEtherium/blockchain/node_modules/web3-core/lib/index.js:27:15)
    at Web3 (/Users/username/Blockchain/BlockchainEtherium/blockchain/node_modules/web3/lib/index.js:39:10)
    at Object.<anonymous> (/Users/username/Blockchain/BlockchainEtherium/blockchain/test/inbox.test.js:5:14)
    at Module._compile (node:internal/modules/cjs/loader:1112:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1166:10)
    at Module.load (node:internal/modules/cjs/loader:988:32)
    at Function.Module._load (node:internal/modules/cjs/loader:834:12)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:170:29)
    at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
    at async Promise.all (index 0)
    at ESMLoader.import (node:internal/modules/esm/loader:409:24)
    at importModuleDynamicallyWrapper (node:internal/vm/module:438:15)
    at formattedImport (/Users/username/Blockchain/BlockchainEtherium/blockchain/node_modules/mocha/lib/nodejs/esm-utils.js:7:14)
    at Object.exports.requireOrImport (/Users/username/Blockchain/BlockchainEtherium/blockchain/node_modules/mocha/lib/nodejs/esm-utils.js:38:28)
    at Object.exports.loadFilesAsync (/Users/username/Blockchain/BlockchainEtherium/blockchain/node_modules/mocha/lib/nodejs/esm-utils.js:91:20)
    at singleRun (/Users/username/Blockchain/BlockchainEtherium/blockchain/node_modules/mocha/lib/cli/run-helpers.js:125:3)
    at Object.exports.handler (/Users/username/Blockchain/BlockchainEtherium/blockchain/node_modules/mocha/lib/cli/run.js:370:5)

Looking forward to your help.

Thanks

CodePudding user response:

Just initiate web3 with the new keyword as the error suggests.

Change

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

To

const web3 = new Web3(ganache.provider());
  • Related