我想测试我的函数getData()。这个函数用于从我的智能合同中获取数据‘成本’(应该是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');
});测试进入“尝试”,但停止等待contract.cost();并捕获错误:无法检测网络

如何模拟网络窗口。以太/提供者/合同从图书馆?
发布于 2022-10-10 14:21:44
我找到了一个解决方案:我正在使用eth测试包来模拟提供者和合同交互:
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://stackoverflow.com/questions/73996929
复制相似问题