首页 > 解决方案 > 如何使用 jest 和酶在 reactJs 中构建测试用例以使用 fetch 调用进行测试

问题描述

我有以下代码

getFullName() {

    var urlendPoint = new URL(propertiesInFile.urltoPing)

    var params = {
      firstName: this.state.firstName,
      lastName: this.state.lastName
    }

    urlendPoint.search = new URLSearchParams(params)

    fetch(urlendPoint).then(response => response.json()).then((data) => {
        ...perform some actions...
      }
    })
      .catch(error => {
        alert("Please check the names and try again");
      });
  }

propertiesInFile 只是我在另一个 js 文件中定义的硬编码值。

在上面的代码中,我似乎无法模拟 fetch 调用。我如何在反应中测试这个函数,以便我可以获得函数中的状态(名字和姓氏),覆盖 catch 块并尝试到位的 fetch 调用。

标签: reactjsjestjsenzyme

解决方案


在您的测试中,您可以将 fetch 分配给类似这样的模拟函数

global.fetch = jest.fn().mockImplementation(() => mockFetchPromise);

您可以在此网站上找到更多详细信息


推荐阅读