0

I have a function which mints when 1 eth is send to it. The function is

    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");
           .........
        }

I want to write a test which checks if 1 eth is send to it or not. Please help if anyone can.

4
  • You said you want a test, in mocha, to see if the user sent 1 ether. But this is confusing. Mocha is for testing if a function is properly working or not, and not to check if a user sent 1 ether. I will supose you want to know if the function worked correctly. So you need to do a test that sends less than 1 ether and see if it reverted, and then call the function passing more than 1 ether and see if the function passed. Is this what you want? Feb 16, 2022 at 12:38
  • My function should accept exactly 1 ETH neither less nor more. Rest you got it right.
    – Haris
    Feb 16, 2022 at 12:54
  • then you should check the balance of the contract before (the contract is an account, so it will have a balance), the balance of the contract after, and assert if the difference in balance 1 ether. Feb 16, 2022 at 13:00
  • This is also a good solution. Thanks
    – Haris
    Feb 16, 2022 at 13:04

2 Answers 2

0

You got the right idea, just keep in mind ETH has 18 decimals.

require(msg.value >= 1 * 10**18, "Must send at least 1 ETH");
2
  • I want to write a test to validate this. How can I write this test logic in mocha? This is the question.
    – Haris
    Feb 16, 2022 at 12:09
  • 2
    Solidity accepts the keyword ether and does the conversion Feb 16, 2022 at 12:32
0

Answer I finally figured it out. This is how I wrote test for this case.

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");
  })
});

I'm checking for 1 WEI instead of 1 ETH in this case to avoid BigNumber Error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.