我想測驗我的函式 getData()。該函式用于從我的智能合約中獲取資料“cost”(應該是 5)和“totalSupply”(應該是 50)。
getData: async function(){
if(typeof window.ethereum !== 'undefined') {
const provider = new ethers.providers.Web3Provider(window.ethereum);
const contract = new ethers.Contract(this.contractAddress, NftContract.abi, provider); //new instance of the contract to interact with the function of the contract
try {
console.log('*******try');
const cost = await contract.cost();
const totalSupply = await contract.totalSupply();
console.log('*******cost');
console.log(cost);
this.data.cost = String(cost);
this.data.totalSupply = String(totalSupply);
}
catch(err) {
console.log('error');
console.log(err);
this.setError('An error occured to get the data');
}
}
}
我的測驗如下:
it('getData function should affect the cost and totalSupply to the data', async () => {
window.ethereum = jest.fn();
let ethers = {
providers: {
Web3Provider: jest.fn()
},
Contract: jest.fn()
}
let contract = {
cost: jest.fn(),
totalSupply: jest.fn()
};
const costMocked = 5;
const totalSupplyMocked = 50;
contract.cost.mockResolvedValue(costMocked);
contract.totalSupply.mockResolvedValue(totalSupplyMocked);
await wrapper.vm.getData();
expect(wrapper.vm.data.cost).toBe('5');
expect(wrapper.vm.data.totalSupply).toBe('50');
});
測驗進入“嘗試”,但在 await contract.cost() 處停止;并捕獲錯誤:無法檢測到網路![錯誤:無法檢測到網路 [jest] [ethers] [javascript]](https://img.uj5u.com/2022/10/12/d30ee6b0bc524643b91d7cca51855963.png)
如何從庫 ethers 模擬網路 windows.ethereum/provider/contract?
uj5u.com熱心網友回復:
我找到了一個解決方案:我正在使用 eth-testing 包來模擬提供者和合同互動:
it('getData function should affect the cost and totalSupply to the data', async () => {
// Start with not connected wallet
testingUtils.mockNotConnectedWallet();
// Mock the connection request of MetaMask
testingUtils.mockRequestAccounts(["0xe14d2f7105f759a100eab6559282083e0d5760ff"]);
//allows to mock the chain ID / network to which the provider is connected --> 0x3 Ropsten network
testingUtils.mockChainId("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);
await contractTestingUtils.mockCall("cost", [5]);
await contractTestingUtils.mockCall("totalSupply", [50]);
await wrapper.vm.getData();
expect(wrapper.vm.data.cost).toBe('5');
expect(wrapper.vm.data.totalSupply).toBe('50');
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/513963.html
標籤:javascript单元测试开玩笑的ethers.js
