【合约开发工具】如何使用 hardhat 在本地测试合约

前言

本文介绍如何使用 hardhat 在 solidity 项目中本地测试智能合约,并介绍一些简要的写法。

基本配置

在本地测试与部署前,需要认识与安装一些 hardhat 的插件。

  • hardhat-ethers
    安装:
    npm install -D hardhat-deploy
    npm install --save-dev @nomiclabs/hardhat-ethers 'ethers@^5.0.0'
    npm install --save-dev @nomiclabs/hardhat-ethers@npm:hardhat-deploy-ethers ethers
    安装插件的主要目的是能让我们在 test script 中方便的模拟合约与部署。

TIPS: 若使用了 hardhat-deploy-ethers 插件,会有些功能用不了,这是因为 hardhat-deploy-ethers 作为 hardhat-ethers 的一个 fork,还有很多不完善的 hardcode 在代码中。
虽然目前没有解决办法,但官方说以后会作为扩展兼容。

之后,在 hardhat.config.ts 中,import 依赖。

这点很重要,一定要在配置文件中import,其他地方配置 hardhat 会因为读不到类型而报错。

测试代码

sample.test.ts

import {
    
    expect} from "./chai-setup";
//ethers的引入很重要,许多功能都由其提供。
import {
    
    deployments, ethers, getNamedAccounts} from 'hardhat';
import {
    
    BigNumber, Contract} from "ethers";

//测试使用的是基础的js测试框架 -- mocha
//具体语法参考:https://mochajs.cn/
describe("Greeter", function() {
    
    

  let greeter: Contract;

  it("Should return the new greeting once it's changed", async function() {
    
    

    greeter = await (await ethers.getContractFactory('Greeter')).deploy("Hello, world!");
    await greeter.deployed();
    expect(await greeter.greet()).to.equal("Hello, world!");

    const setGreetingTx = await greeter.setGreeting("Hola, mundo!");
    // wait until the transaction is mined
    await setGreetingTx.wait();
    expect(await greeter.greet()).to.equal("Hola, mundo!");
  });
});

本地测试

npx hardhat test

测试结果如图:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43742184/article/details/118397073