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

Time:09-04

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.

I will be glad if someone can guide me and show me my mistake, Thank you!

CodePudding user response:

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[] = [];

CodePudding user response:

Thank you for guidance. Here is the final working version of the code:

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

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

describe("Basic Test", () => {
    beforeEach(async () => {
        const signersArray = await ethers.getSigners()
        await Promise.all(
            signersArray.map(async (i) => {
                addresses.push(await i.getAddress())
            })
        )
    })
    it("Prints every address that we have", () => {
        console.log(addresses)
    })
})

  • Related