首页 > 解决方案 > “获取”未定义

问题描述

我有这段代码,我正在用 HTMLUnit 测试:

function fetchIt() {
    var response = fetch('https://httpbin.org/get');
    var json = response.json();
    console.log(json);
    return json;
};
fetchIt();

但是抛出

net.sourceforge.htmlunit.corejs.javascript.EcmaError: ReferenceError: "fetch" is not defined.

我们如何使用fetchHTMLUnit、JUnit 进行测试?

fetchhttps://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

标签: javascriptjavajunithtmlunit

解决方案


使用HtmlUnit测试代码意味着您不在具有fetch 功能的浏览器中。

您应该在页面中包含用于 fetch 的 polyfill,或使其在单元测试上下文中可用。


推荐阅读