I'm having an issue with running truffle test on a Javascript test. I get the error TypeError: Cannot read property 'getBlock' of undefined.

I am trying to get the time of the latest block by using a snippet from OpenZeppelin:

async function latestTime () {
  const block = await web3.eth.getBlock('latest');
  return block.timestamp;

When I run this in truffle console, web3.eth.getBlock('latest') works fine.


The error message implies that web3.eth has not been defined in your JavaScript context.

Make sure you are also including the code which adds the web3 provider:

window.addEventListener('load', function() {

  // Checking if Web3 has been injected by the browser (Mist/MetaMask)
  if (typeof web3 !== 'undefined') {
    // Use Mist/MetaMask's provider
    web3 = new Web3(web3.currentProvider);
  } else {
    console.log('No web3? You should consider trying MetaMask!')
    // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
    web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

  // Now you can start your app & access web3 freely:


From here: Web3 - Ethereum Browser Environment Check

EDIT: For developing in truffle, the code would look something like this:

  initWeb3: function () {
    // Is there an injected web3 instance?
    if (typeof web3 !== 'undefined') {
      App.web3Provider = web3.currentProvider;
    } else {
      // If no injected web3 instance is detected, fall back to Ganache
      App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
    web3 = new Web3(App.web3Provider);

    return App.initContract();
  • I'm doing this inside of a truffle test. Truffle's documentation says that they inject web3, so should I have to do this inside of their framework? – adi Jul 11 '18 at 22:37
  • Yes. Even within truffle, you will need to inject a Web3 instance, see my edit above. Also check out this documentation and this tutorial. – Shawn Tabrizi Jul 11 '18 at 22:54

My issue was a versioning problem truffle console was running web3 1.0 while my tests were accessing an injected web3 0.20 instance. This mean that when I ran my test in an interactive console, it would succeed, but obviously fail when I ran it using truffle test.

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.