Testing

如何使用 ethers.js 測試發送 eth 的功能?

  • February 27, 2022

我對 eth dev 很感興趣,並嘗試在為betOnTeam函式分配值的同時測試發送 eth:

function betOnTeam(uint8 _team) public payable {
  // assign usre to _team and add betting value to totalBetsOne 
}

function AmountOne() public view returns (uint256) {
   return totalBetsOne;
} 

我用安全帽編寫的測試:

const { expect } = require("chai");
const { ethers } = require("hardhat");


let betting;
let owner;
let addr1;
let addr2;
let addrs;

beforeEach(async function () {
 Betting = await ethers.getContractFactory("Betting");
 [owner, addr1, addr2, ...addrs] = await ethers.getSigners();
 betting = await Betting.deploy();
});

describe("Deployment", function () {
 it("Should set the right owner", async function () {
   expect(await betting.owner()).to.equal(owner.address);
 });
 it("Initial bet values should be zero", async function () {
  // const ownerBalance = await betting.balanceOf(owner.address);
   expect(await betting.AmountOne()).to.equal(0);
   expect(await betting.AmountTwo()).to.equal(0);
 });
});

describe("User1 bets on team1", function () {
 it("Should transfer eth from User1 to the contract", async function () {
   //user 1 makes a 3 eth bet on team one 
   const makeABet = await betting.connect(addr1).betOnTeam(1, {from: addr1.address, value: 3});

   await makeABet.betOnTeam(1);
   const newAmountOne = await betting.AmmountOne(); 
   expect(newAmountOne).to.equal(3);
 });
  
});

但是測試失敗並出現以下錯誤:

Deployment
   ✓ Should set the right owner
   ✓ Initial bet values should be zero

 User 1 bets on team 1
   1) Should transfer eth from User1 to the contract


 2 passing (664ms)
 1 failing

 1) User 1 bets on team 1
      Should transfer eth from User1 to the contract:
    Error: Transaction reverted without a reason string
     at Betting.betOnTeam (contracts/Betting.sol:48)
     at processTicksAndRejections (node:internal/process/task_queues:96:5)
     at runNextTicks (node:internal/process/task_queues:65:3)
     at listOnTimeout (node:internal/timers:526:9)
     at processTimers (node:internal/timers:500:7)
     at HardhatNode._mineBlockWithPendingTxs (node_modules/hardhat/src/internal/hardhat-network/provider/node.ts:1649:23)
     at HardhatNode.mineBlock (node_modules/hardhat/src/internal/hardhat-network/provider/node.ts:458:16)
     at EthModule._sendTransactionAndReturnHash (node_modules/hardhat/src/internal/hardhat-network/provider/modules/eth.ts:1496:18)

我想知道測試中有什麼問題,我該如何解決?

好的,謝謝這個人,我找到了答案:

describe("User 1 bets on team 1", function () {
 it("Should transfer eth from User1 to the contract", async function () {
   //user 1 makes a bet on team one 
   await betting.connect(addr1).betOnTeam(1, {value: 3});

   const newAmountOne = await betting.AmountOne(); 
   expect(newAmountOne).to.equal(3);
 });
  
});

引用自:https://ethereum.stackexchange.com/questions/117641