Solidity

如何測試 msg.value 在測試中是否為 1 ether

  • February 16, 2022

我有一個功能,當 1 eth 發送給它時它會鑄造。功能是

   function _mint() public payable{
           require(msg.value == 1 ether , "Send more ethers: 1 ether is required");
           require(balanceOf(msg.sender)==0, "You can not have more than 1 Land");
          .........
       }

我想編寫一個測試來檢查 1 eth 是否發送給它。如果有人可以,請提供幫助。

你的想法是對的,請記住 ETH 有 18 位小數。

require(msg.value >= 1 * 10**18, "Must send at least 1 ETH");

答案 我終於想通了。這就是我為這個案例編寫測試的方式。

describe("Amount Received",()=>{
 it("Should only mint When 1 Eth is received",async()=>{
   let v = await (contractInstance._mint({value:1}));
   v.wait();
    expect( v.value.toString()).to.equal("1");
 })
});

在這種情況下,我正在檢查 1 WEI 而不是 1 ETH,以避免出現 BigNumber 錯誤。

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