I am trying to write Hardhat tests with TypeScript and am struggling with the scope of (thus accessing) certain variables. I have provided a simplified snippet of what I am struggling with.
Below, is the example that works. Declaring and assigning accountOne
in the same unit test I need it in. However, I need the variable in more than one test, so I need to change its scope to be accessible in more than one test. This way I can avoid having to repeat the same lines of code over and over.
import { ethers } from "hardhat";
import { Signer } from "ethers";
describe("Runs unit tests with Hardhat", () => {
it("Logs accountOne's address from Hardhat", async () => {
const [accountOne] = await ethers.getSigners();
console.log(accountOne.address);
});
})
Below is my attempt at declaring and assigning it in the before
hook's block of code. It didn't work because it is a local variable to that block. (I've also tried using a beforeEach
hook to similar results.) However, I've done it this way using JavaScript, and it worked previously, so I assumed it would work with TypeScript. This logs Cannot find name 'accountOne'.
import { ethers } from "hardhat";
import { Signer } from "ethers";
describe("Runs unit tests with Hardhat", () => {
before(async () => {
const [accountOne] = await ethers.getSigners();
});
it("Logs accountOne from Hardhat", () => {
console.log(accountOne.address);
});
})
Below, is an attempt at accessing accountOne
in the unit test. I declared it in the describe
block of code with a type of Signer
, assigned it a value in the before
hook, then used it in the unit test I needed. This is the one I am least sure about because I am declaring accountOne
as type Signer
, when the signers are originally created from calling ethers.getSigners()
. This logs Property 'address' does not exist on type 'Signer'.
import { ethers } from "hardhat";
import { Signer } from "ethers";
describe("Runs unit tests with Hardhat", () => {
let accountOne : Signer;
before(async () => {
accountOne = await ethers.getSigners();
});
it("Logs accountOne from Hardhat", () => {
console.log(accountOne.address);
});
})
Below is my most recent attempt, in which I declared and assigned accountOne
a value in the describe
block, then access it in the unit test. This logs nothing to the console.
import { ethers } from "hardhat";
import { Signer } from "ethers";
describe("Runs unit tests with Hardhat", async () => {
const [accountOne] = await ethers.getSigners();
it("Logs accountOne from Hardhat", () => {
console.log(accountOne.address);
});
})
I am currently learning TypeScript, so that is where I believe the issue lies. Also, because I didn't encounter this issue when writing tests in JavaScript.