【问题标题】:How to mock a transaction with a smart contract with eth-testing如何通过带有道德测试的智能合约模拟交易
【发布时间】:2023-01-10 05:50:57
【问题描述】:

我想测试我的 Vue 应用程序的 mint 功能。调用此函数时,用户应该能够铸造 NFT。为此,我需要调用智能合约的 mint 函数。

mint: async function(){
  if(typeof window.ethereum !== 'undefined') {
    let accounts = await window.ethereum.request({method : 'eth_requestAccounts'});
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const signer = provider.getSigner();
    const contract = new ethers.Contract(this.contractAddress, NftContract.abi, signer);
    try {
      let overrides = {
        from: accounts[0],
        value: this.data.cost
      }
      //error to mock the transaction
const transaction = await contract.mint(accounts[0], 1, overrides);
          await transaction.wait();
          this.getData();
          this.setSuccess('The NFT mint is successful');
        }
        catch(err) {
          console.log(err);
          this.setError('An error occured to mint');
        }
      }
    }

我的智能合约的铸币功能:

  function mint(address _to, uint256 _mintAmount) public payable {
    uint256 supply = totalSupply();
    require(!paused);
    require(_mintAmount > 0);
    require(_mintAmount <= maxMintAmount);
    require(supply + _mintAmount <= maxSupply);

    if (msg.sender != owner()) {
        if(whitelisted[msg.sender] != true) {
          require(msg.value >= cost * _mintAmount);
        }
    }

    for (uint256 i = 1; i <= _mintAmount; i++) {
      _safeMint(_to, supply + i);
    }
  }

我正在使用 eth-testing 库 (https://www.npmjs.com/package/eth-testing?activeTab=readme) 来模拟我的智能合约交互。

最初,我的合约的总供应量是 5。在函数调用和 1 NFT 铸造之后,它应该返回总供应量 6。 我对 Jest 的测试如下:

  it('when the user mint 1 NFT, the totalSupply should increment and a successful message should appear (mint funtion)', async () => {
// Start with not connected wallet
testingUtils.mockNotConnectedWallet();
// Mock the connection request of MetaMask
const account = testingUtils.mockRequestAccounts(["0xe14d2f7105f759a100eab6559282083e0d5760ff"]);
//allows to mock the chain ID / network to which the provider is connected --> 0x3 Ropsten network
testingUtils.mockChainId("0x3");
// Mock the network to Ethereum main net
testingUtils.mockBlockNumber("0x3");

const abi = NftContract.abi;
// An address may be optionally given as second argument, advised in case of multiple similar contracts
const contractTestingUtils = testingUtils.generateContractUtils(abi);
let transaction;
//transaction = await contractTestingUtils.mockCall("mint", account, String('10000000000000000')); //Invalid argument
//transaction = await contractTestingUtils.mockCall("mint"); //bad result from back end
//transaction = await contractTestingUtils.mockCall("mint", [account, 1, ethers.utils.parseUnits("0.01", "ether")]); //Invalid argument
//transaction = await contractTestingUtils.mockTransaction("mint"); //Cannot read properties of undefined (reading 'toLowerCase')
transaction = await contractTestingUtils.mockTransaction("mint", undefined, {
    triggerCallback: () => {
      contractTestingUtils.mockCall("cost", ['10000000000000000']);
      contractTestingUtils.mockCall("totalSupply", ['5']);
    }
}); //Cannot read properties of undefined (reading 'toLowerCase')

await wrapper.vm.mint();
await wrapper.vm.getData();

console.log('********wrapper.vm.data');
console.log(wrapper.vm.data);

expect(wrapper.vm.data.totalSupply).toBe('6');
});

我不明白如何模拟我的交易,我尝试了一些解决方案但有错误。

【问题讨论】:

    标签: javascript unit-testing jestjs smartcontracts jest-fetch-mock


    【解决方案1】:

    我也在学习,我想我会尝试帮助解决似乎对我有用的事情......从我到目前为止所了解的情况来看,你需要合同的能力。对我来说,在 artifacts/contracts/{YourContractName}.sol 下生成并找到了 using hardhat。我将其保存到名为 ABI 的夹具文件中,并将其导入到我的测试中。然后我可以使用 mockNFT 执行 mockContract.mockCall("mintNFT", [transaction]); 我想要模拟的函数名称,它包含在 ABI 中并返回一个事务。 (交易保存在一个变量中,这是一个可行的交易哈希)。您可能还想考虑做一些类似于here 的示例,它的工作方式类似于testingUtils.generateContractUtils(ABI).mockTransaction("mintNFT");,而 testingUtils 是来自 libs 方法generateTestingUtils 的 var。

    【讨论】:

      猜你喜欢
      • 2019-01-17
      • 1970-01-01
      • 2021-04-03
      • 2018-07-18
      • 2021-10-29
      • 2020-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多