javascriptethereumsoliditysmartcontractshardhat

Importing ethers via Hardhat fails despite official testing documentation


According to the official testing documentation for Hardhat, ethers should be available implicitly within the global scope; however, it can optionally be required explicitly, like so:

const { ethers } = require("hardhat");

This fails for my local project.

My package manifest seems to include the correct dependencies:

{
  "dependencies": {
    "@nomiclabs/hardhat-ethers": "^2.0.1",
    "@nomiclabs/hardhat-waffle": "^2.0.1",
    "@openzeppelin/contracts": "https://github.com/OpenZeppelin/openzeppelin-contracts#v4.0.0-beta.0",
    "chai": "^4.3.1",
    "hardhat": "^2.0.11"
  }
}

My unit tests file seems to match the worked example in the Hardhat documentation also:

const { ethers } = require("hardhat");
const { expect } = require("chai");

describe("Distributor.sol", function() {
    it("Distribution should fail for non-owners", async function() {
        const DistributorFactory = await ethers.getContractFactory("Distributor");
        const Distributor = await Distributor.deploy();

        Distributor.distribute([], []);

        expect(await hardhatToken.totalSupply()).to.be.revertedWith("foobar");
    });
});

Despite this, running the tests fails with:

$ yarn hardhat test
yarn run v1.22.5
$ /home/bob/dev/misc/token-distributor/node_modules/.bin/hardhat test


  Distributor.sol
undefined
    1) Distribution should fail for non-owners


  0 passing (9ms)
  1 failing

  1) Distributor.sol
       Distribution should fail for non-owners:
     TypeError: Cannot read property 'getContractFactory' of undefined
      at Context.<anonymous> (test/Distributor.js:8:49)
      at processImmediate (internal/timers.js:461:21)



error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

How do I fix this?


Solution

  • Add the require in your hardhat.config.js

    require("@nomiclabs/hardhat-waffle");
    

    And remove this line from your test file:

    const { ethers } = require("hardhat");
    

    Then, you can use ethers in your tests. Hardhat looks in the config first before running tests. If you have required a package that includes ethers you can use it in the global scope.