我有一个React Native项目,其中只包含使用新项目创建的示例Jest测试(它们仅检查在iOS和Android上渲染是否正常)。
我的项目在一个组件中使用fetch进行网络请求。当我运行应用程序时,这个功能可以正常工作,但是当我运行测试时,它们会失败,并显示以下错误信息:
TypeError: fetch is not a function.
有人知道发生了什么吗?
这是我的代码部分,使用了fetch:
我的项目在一个组件中使用fetch进行网络请求。当我运行应用程序时,这个功能可以正常工作,但是当我运行测试时,它们会失败,并显示以下错误信息:
TypeError: fetch is not a function.
有人知道发生了什么吗?
这是我的代码部分,使用了fetch:
export default class MainScene extends Component {
constructor(props) {
super(props);
this.renderRowView = this.renderRowView.bind(this);
}
onFetch(page = 1, callback) {
var date = new Date();
date.setDate(date.getDate() - 7);
fetch( url, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then((response) => response.json())
.then((responseJson) => {
if (responseJson.response.pages <= page) {
callback(responseJson.response.results, {
allLoaded: true
});
} else {
callback(responseJson.response.results);
}
})
.catch((error) => {
console.error(error);
});
}}
测试文件:
import 'react-native';
import React from 'react';
import Index from '../index.ios.js';
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
require
,所以我的问题似乎不同。 - Mihai Damianfetch
是 React Native 自带的,但是 NodeJS 没有(我猜 Jest 是运行在 NodeJS 上的,但我自己从未使用过)。尝试为你的测试添加一个fetch
polyfill。 - Bruno Grieder