第2节:单元测试

小白入门:https://github.com/dukedaily/solidity-expert ,欢迎star转发,文末加V入群。

职场进阶: https://dukeweb3.com

  1. 涉及到revertedWith和emit时,需要:
    • 将await写在expect外面,里面不需要写await了
    • .to.revertedWith,不是.be.revertedWith:
    describe('Create Offer', () => {
        it.only('should faild to call createOffer directly', async () => {
            let last = await getOffer(lastOffer)
            await expect(last.createOffer(tokens, info)).to.revertedWith("Bazaar: permission denied")
        })
    })
  1. 测试单个文件
npx hardhat test test/xxx.spec.ts
  1. 如果测试过程中需要改变块高
async function mineBlocks(blockNumber) {
  while (blockNumber > 0) {
    blockNumber--;
    await hre.network.provider.request({
      method: "evm_mine",
    });
  }
}
  1. 如果单元测时,不去执行it内部逻辑,可能是:it错误的写成了if,或者没有使用beforeEach,或者没有试用loadFixture

  2. Sometimes when we run test, it takes very long to execute why? (network issue, disconnect the network may work)

  3. Be sure never call any function(make any assignment) out side of beforeEach or a describe or it will fail

    describe("Rivers", async function () {
      let accounts: SignerWithAddress[]
      let compIns: Comp
      let unitrollerIns: Unitroller
      let comptrollerIns: Comptroller
      let sPriceOracleIns: SimplePriceOracle
      let container: Box[] = [];
      // accounts = await hre.ethers.getSigners();  <-- error
    
      beforeEach(async () => {
        console.log("begin beforeEach");
        accounts = await hre.ethers.getSigners();
        console.log("accounts len: ", accounts.length);
    
        await loadFixture(deployOpenEdenFixture);
      })
    })