[Contract Development Tools] How to use hardhat to test contracts locally

foreword

This article introduces how to use hardhat to test smart contracts locally in solidity projects, and introduces some brief writing methods.

basic configuration

Before testing and deploying locally, you need to know and install some hardhat plug-ins.

  • hardhat-ethers
    installation:
    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
    The main purpose of installing the plug-in is to allow us to conveniently simulate the contract and deploy it in the test script.

TIPS: If you use the hardhat-deploy-ethers plug-in, some functions will not be available. This is because hardhat-deploy-ethers is a fork of hardhat-ethers, and there are still many imperfect hardcodes in the code.
Although there is no solution at present, the official said that it will be compatible as an extension in the future.

After that, in hardhat.config.ts, import dependency.

This is very important. It must be imported in the configuration file. If hardhat is configured in other places, an error will be reported because the type cannot be read.

test code

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!");
  });
});

local test

npx hardhat test

The test results are shown in the figure:
insert image description here

Guess you like

Origin blog.csdn.net/weixin_43742184/article/details/118397073