【Hardhat 运行测试】

本文介绍了如何在Hardhat环境中使用Mocha框架编写和运行针对SoliditySimpleStorage合约的测试,包括部署合约、执行存储和检索操作,并演示了指定测试的两种方法:grep和it.only。
  • 删除artifacts和缓存
> yarn hardhat clean
const { ethers } = require("hardhat")
const { assert, expect } = require("chai")

// Mocha 测试框架会识别这个describe函数
describe("SimpleStorage", function () {
  let simpleStorageFactory, simpleStorage
  beforeEach(async function () {
    simpleStorageFactory = await ethers.getContractFactory("SimpleStorage")
    simpleStorage = await simpleStorageFactory.deploy()
  })

  // 测试做什么,用函数来实际执行这个操作
  it("Should start with a favorite number of 0", async function () {
    const currentValue = await simpleStorage.retrieve()
    const expectedValue = "0"
    assert.equal(currentValue.toString(), expectedValue)
    // expect(currentValue.toString()).to.equal(expectedValue) // 等价于上面
  })
  it("Should update when we call store", async function () {
    const expectedValue = "7"
    const transactionResponse = await simpleStorage.store(expectedValue)
    await transactionResponse.wait(1)

    const currentValue = await simpleStorage.retrieve()
    assert.equal(currentValue.toString(), expectedValue)
  })
})
  • 运行命令yarn hardhat test
> yarn hardhat test
yarn run v1.22.19
..\node_modules\.bin\hardhat test


  SimpleStorage
    ✔ Should start with a favorite number of 0
    ✔ Should update when we call store


  2 passing (2s)

Done in 2.28s.
  • 运行指定某一个it测试,【方式一】:使用--grep指定it中的第一个String参数所包含的字符即可,因为store字符在第二个it中存在,因此只测试第二个
> yarn hardhat test --grep store
yarn run v1.22.19
$ E:\web3_solidity\hardhat-solidity01\node_modules\.bin\hardhat test --grep store


  SimpleStorage
    ✔ Should update when we call store


  1 passing (2s)

Done in 2.26s.
  • 运行指定某一个it测试,【方式二】:用it.only来代替it,然后运行命令yarn hardhat test
//test-deploy.js
it.only("Should start with a favorite number of 0", async function () {
    const currentValue = await simpleStorage.retrieve()
    const expectedValue = "0"
    assert.equal(currentValue.toString(), expectedValue)
})
> yarn hardhat test
yarn run v1.22.19
..\node_modules\.bin\hardhat test


  SimpleStorage
    ✔ Should start with a favorite number of 0


  1 passing (2s)

Done in 2.24s.
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值