I want to test my function getData(). This function is used to get the data 'cost' (should be 5) and 'totalSupply' (should be 50) from my smart contract.
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');
}
}
}
My test is the following:
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');
});
The test enters into the 'try' but stop at await contract.cost(); and catch the error: could not detect network
How to mock a network windows.ethereum/provider/contract from the library ethers?
CodePudding user response:
I found a solution: I'm using eth-testing package to mock the provider and contract interaction:
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');
});