javascript - 类型错误 : Cannot read properties of undefined (reading 'getContractFactory' ) when testing contract

标签 javascript solidity

如果不是很清楚,第一个问题就这么简单,但我会尽力而为。

我目前正在浏览 youtube 视频,以测试我与安全帽、以太币和华夫饼 (https://www.youtube.com/watch?v=oTpmNEYV8iQ&list=PLw-9a9yL-pt3sEhicr6gmuOQdcmWXhCx4&index=6) 的契约(Contract)。

这是契约(Contract):

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.9;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";

contract MyContract is ERC721 {

  constructor(string memory name, string memory symbol) 
    ERC721(name, symbol) {

    }
  
}

这里是 test.js:

const { expect } = require('chai');

describe("MyContract", function() {
  
  it("should return correct name", async function() {
    const MyContract = hre.ethers.getContractFactory("MyContract");
    const myContractDeployed = await MyContract.deploy("MyContractName", "MCN");
    await myContractDeployed.deployed();
    
    expect(await myContractDeployed.name()).to.equal("MyContractName");
  });
});

当我在终端中运行“npx hardhat test”时,它返回:

MyContract
    1) should return correct name


  0 passing (7ms)
  1 failing

  1) MyContract
       should return correct name:
     TypeError: Cannot read properties of undefined (reading 'getContractFactory')
      at Context.<anonymous> (test\test.js:7:35)
      at processImmediate (node:internal/timers:464:21)

我的代码与视频中的代码相匹配,但我很难理解为什么会出现 TypeError。非常感谢任何指导!

编辑:

我以某种方式修复了它,我不明白它究竟是如何修复它的,但确实如此。而不仅仅是安装

npm install @nomiclabs/hardhat-waffle ethereum-waffle chai @nomiclabs/hardhat-ethers ethers

我安装了

npm install --save-dev @nomiclabs/hardhat-waffle ethereum-waffle chai @nomiclabs/hardhat-ethers ethers

然后终端打印出来

npm WARN idealTree Removing dependencies.@nomiclabs/hardhat-waffle in favor of devDependencies.@nomiclabs/hardhat-waffle
npm WARN idealTree Removing dependencies.ethereum-waffle in favor of devDependencies.ethereum-waffle
npm WARN idealTree Removing dependencies.@nomiclabs/hardhat-ethers in favor of devDependencies.@nomiclabs/hardhat-ethers
npm WARN idealTree Removing dependencies.ethers in favor of devDependencies.ethers

然后我删除了 ethers.getContractFactory("MyContract") 前面的 hre,它起作用了!如果有人想解释为什么这可能会解决它,我很乐意阅读它,否则我将继续前进。

最佳答案

在您的 hardhat.config.js 文件顶部添加以下代码片段

require("@nomiclabs/hardhat-waffle");

关于javascript - 类型错误 : Cannot read properties of undefined (reading 'getContractFactory' ) when testing contract,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70628980/

相关文章:

javascript - 在vue中执行嵌套函数

javascript - 使用 React 和 NodeJS 的注册表单 - 我的 axios 请求出了什么问题?

javascript - 数组映射迭代有什么问题

ethereum - 调用外部契约(Contract)抛出错误 : VM Exception while processing transaction: revert

javascript - 替换多次出现的动态字符串?

java - 防止 HtmlUnit 2.13 执行 JavaScript

solidity - 如何将 SafeMath.sol 正确导入合约

ethereum - ERC-721 智能合约一次类型转换 2 个 NFT

ethereum - 只读函数迭代成本

solidity - 交易无法解码 : could not recover secp256k1 key: calculated Rx is larger than curve P