typescript 停留在基本的ethers.js/hardhat问题上|控制台记录我的阵列导致未定义

qvk1mo1f  于 2022-12-19  发布在  TypeScript
关注(0)|答案(2)|浏览(221)

大家好,我正在使用Typescript玩hardhat/ethers.js,但是被卡住了。
以下是我的***导入:***

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 () => {
        signersWithAddress = await ethers.getSigners()
        signersWithAddress.map(async (_signer: SignerWithAddress) =>
            addresses.push(await _signer.getAddress())
        )
    })
    it("Prints every address that we have", () => {
        console.log(addresses)
    })
})

当我在我的终端上运行Yarn安全帽测试时,我得到这个输出(undefined来自console.log):

Basic Test
undefined
    ✔ Prints every address that we have

  1 passing (719ms)

Done in 2.85s.

错误在哪里?如何纠正?

h6my8fg2

h6my8fg21#

let addresses: string[]不初始化addresses为任何东西,所以除非有东西分配一个数组给变量,它将只是undefined . addresses.push(await _signer.getAddress())不分配一个新的数组给变量,如果它是undefined .你需要手动地做.只是尝试做以下在你的浏览器控制台:

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

相反,您应该:

let signersWithAddress: SignerWithAddress[] = [];
vc9ivgsu

vc9ivgsu2#

感谢您的指导。以下是代码的最终工作版本:

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)
    })
})

相关问题