How do I access a web3 instance from inside a Truffle Javascript test?


It turns out that Truffle automatically injects web3 into the Javascript test file. Simply use it directly as follows:

//  test/mycontract.js


contract("MyContract", accounts => {
  var accountA = accounts[0];

  it("...should...", async () => {

    const accountABalance = await web3.eth.getBalance(accountA);


At the top of your truffle .js file you can write:

const Web3 = require('web3');
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:9545'));

And in one of your it test blocks, you can then use web3.[desired func].

  • 2
    Thanks! But it turns out Truffle automatically injects web3.
    – Tarek
    Sep 10 '18 at 23:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.