首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >错误:无法检测到网络[jest] [ether] [javascript]

错误:无法检测到网络[jest] [ether] [javascript]
EN

Stack Overflow用户
提问于 2022-10-08 12:20:25
回答 1查看 41关注 0票数 -1

我想测试我的函数getData()。这个函数用于从我的智能合同中获取数据‘成本’(应该是5)和'totalSupply‘(应该是50)。

代码语言:javascript
复制
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');
    }
  }
}

我的测试如下:

代码语言:javascript
复制
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();并捕获错误:无法检测网络

如何模拟网络窗口。以太/提供者/合同从图书馆?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-10 14:21:44

我找到了一个解决方案:我正在使用eth测试包来模拟提供者和合同交互:

代码语言:javascript
复制
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');
  });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73996929

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档