Search code examples
typescriptmocha.jssolidityethers.jshardhat

Stuck at a basic ethers.js/hardhat problem | Console logging my array results in undefined


Hello guys I was playing around with hardhat/ethers.js using Typescript but got stuck on.

Here are my imports:

import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"
import { ethers } from "hardhat"
import { beforeEach, describe, it } from "mocha"

my fullscope variables:

let signersWithAddress: SignerWithAddress[]
let addresses: string[]

And here is my basic mocha test:

describe("Basic Test", () => {
    beforeEach(async () => {
        signersWithAddress = await ethers.getSigners()
        signersWithAddress.map(async (_signer: SignerWithAddress) =>
            addresses.push(await _signer.getAddress())
        )
    })
    it("Prints every address that we have", () => {
        console.log(addresses)
    })
})

When I run yarn hardhat test on my terminal, I get this output(undefined comes from console.log):

 Basic Test
undefined
    ✔ Prints every address that we have


  1 passing (719ms)

Done in 2.85s.

Where is the mistake and how can it be fixed?


Solution

  • let addresses: string[] doesn't initialize addresses to anything, so unless something assigns an array to the variable, it will just be undefined. addresses.push(await _signer.getAddress()) doesn't assign a new array to the variable if it is undefined. you need to do that manually. Just try doing the following in the your browser console:

    let a
    a.push(1) // will error since a is undefined
    

    Instead, you should do:

    let signersWithAddress: SignerWithAddress[] = [];