简体   繁体   中英

How to test a solidity payable function with hardhat

I have the following smart contract function:

 function safeMint(address to, uint256 tokenId) public onlyOwner payable {
    require(msg.value >= mintPrice, "Not enough ETH to purchase NFT; check price!"); 
    _safeMint(to, tokenId);
}

and the following test function in chai to test it.

describe("mint", () => {
  it("should return true when 0.5 ethers are sent with transaction", async function () {
    await contract.deployed();
    const cost = ethers.utils.parseEther("0.1");
    await contract.safeMint("0x65.....",1,cost
  }); 

However the test function is not working and gives me an error on cost. Error: "Type 'BigNumber' has no properties in common with type 'Overrides & { from?: PromiseOrValue; }'." I fail to understand where the error lies.

Try this, it's the valid syntax to send value with the call:

await contract.safeMint("0x65.....", 1, {value: cost});

I had a similar problem while testing a payable function, it kept saying 'object is not an instanceof of BigInt'. How I solved this problem and ensured testing ran smoothly was to test the balance of the receiver (in your case, the 'to' address), to make sure the balance has been updated. That is, if the safeMint function was successful during test, the 'to' address should be increased by 1. You can test by: const balOfToAdress = await contract.balanceOf(to.address) expect(balOfToAddress).to.equal(1)

Note: the 'expect' above is gotten by requiring chai at the top of your code ie const {expect} = require('chai') and, you have to test specifically for the balance of 'to' address (Here, I just assumed the initial balance of mints on 'to' address is 0).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM