머리말
이 글에서는 hardhat을 사용하여 solidity 프로젝트에서 로컬로 스마트 계약을 테스트하는 방법을 소개하고 몇 가지 간단한 작성 방법을 소개합니다.
기본 구성
로컬에서 테스트 및 배포하기 전에 몇 가지 안전모 플러그인을 알고 설치해야 합니다.
- 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
플러그인 설치의 주요 목적은 계약을 편리하게 시뮬레이션하고 테스트 스크립트에 배포할 수 있도록 하는 것입니다.
TIPS: hardhat-deploy-ethers 플러그인을 사용하면 hardhat-deploy-ethers가 hardhat-ethers의 포크이고 아직 코드에 불완전한 하드코드가 많기 때문에 일부 기능을 사용할 수 없습니다.
현재로서는 해결책이 없지만 향후 확장으로 호환될 것이라고 관계자는 말했다.
그런 다음 hardhat.config.ts에서 종속성을 가져옵니다.
이것은 매우 중요합니다 구성 파일에서 가져와야 합니다 다른 위치에 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
테스트 결과는 그림에 나와 있습니다.