簡體   English   中英

如何通過帶有道德測試的智能合約模擬交易

[英]How to mock a transaction with a smart contract with eth-testing

我想測試我的 Vue 應用程序的 mint function。 調用此 function 時,用戶應該能夠鑄造 NFT。 為此,我需要調用智能合約的 mint function。

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

我的智能合約的 mint function:

  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。在 function 的調用和 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');
});

我不明白如何模擬我的交易,我嘗試了一些解決方案但有錯誤。

我也在學習,我想我會嘗試幫助解決似乎對我有用的事情......從我到目前為止所了解的情況來看,你需要合同的能力。 對我來說,在 artifacts/contracts/{YourContractName}.sol 下生成並找到了 using hardhat。 我將其保存到名為 ABI 的夾具文件中,並將其導入到我的測試中。 然后我就可以做mockContract.mockCall("mintNFT", [transaction]); 使用 mockNFT,我想要模擬的 function 名稱包含在 ABI 中並返回一個事務。 (交易保存在一個變量中,這是一個可行的交易哈希)。 您可能還想考慮做一些類似於此處示例的操作,其工作方式類似於testingUtils.generateContractUtils(ABI).mockTransaction("mintNFT"); testingUtils 是來自 libs 方法generateTestingUtils的 var。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM