According to the official testing documentation for Hardhat, ethers
should be available implicitly within the global scope; however, it can optionally be require
d explicitly, like so:
JavaScript
x
2
1
const { ethers } = require("hardhat");
2
This fails for my local project.
My package manifest seems to include the correct dependencies:
JavaScript
1
10
10
1
{
2
"dependencies": {
3
"@nomiclabs/hardhat-ethers": "^2.0.1",
4
"@nomiclabs/hardhat-waffle": "^2.0.1",
5
"@openzeppelin/contracts": "https://github.com/OpenZeppelin/openzeppelin-contracts#v4.0.0-beta.0",
6
"chai": "^4.3.1",
7
"hardhat": "^2.0.11"
8
}
9
}
10
My unit tests file seems to match the worked example in the Hardhat documentation also:
JavaScript
1
14
14
1
const { ethers } = require("hardhat");
2
const { expect } = require("chai");
3
4
describe("Distributor.sol", function() {
5
it("Distribution should fail for non-owners", async function() {
6
const DistributorFactory = await ethers.getContractFactory("Distributor");
7
const Distributor = await Distributor.deploy();
8
9
Distributor.distribute([], []);
10
11
expect(await hardhatToken.totalSupply()).to.be.revertedWith("foobar");
12
});
13
});
14
Despite this, running the tests fails with:
JavaScript
1
24
24
1
$ yarn hardhat test
2
yarn run v1.22.5
3
$ /home/bob/dev/misc/token-distributor/node_modules/.bin/hardhat test
4
5
6
Distributor.sol
7
undefined
8
1) Distribution should fail for non-owners
9
10
11
0 passing (9ms)
12
1 failing
13
14
1) Distributor.sol
15
Distribution should fail for non-owners:
16
TypeError: Cannot read property 'getContractFactory' of undefined
17
at Context.<anonymous> (test/Distributor.js:8:49)
18
at processImmediate (internal/timers.js:461:21)
19
20
21
22
error Command failed with exit code 1.
23
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
24
How do I fix this?
Advertisement
Answer
Add the require in your hardhat.config.js
JavaScript
1
2
1
require("@nomiclabs/hardhat-waffle");
2
And remove this line from your test file:
JavaScript
1
2
1
const { ethers } = require("hardhat");
2
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.