简体   繁体   English

如何用 hardhat 测试 solidity payable function

[英]How to test a solidity payable function with hardhat

I have the following smart contract function:我有以下智能合约 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.和以下测试 function in chai 来测试它。

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.然而,测试 function 不起作用,并给我一个成本错误。 Error: "Type 'BigNumber' has no properties in common with type 'Overrides & { from?: PromiseOrValue; }'."错误:“'BigNumber' 类型与'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'.我在测试应付账款 function 时遇到了类似的问题,它一直说“对象不是 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)也就是说,如果 safeMint function 在测试期间成功,则“to”地址应增加 1。您可以通过以下方式进行测试: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).注意:上面的 'expect' 是通过在代码顶部要求 chai 获得的,即 const {expect} = require('chai') 并且,你必须专门测试'to'地址的余额(在这里,我只是假设“收件人”地址上的铸币初始余额为 0)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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