在React Native和Jest中出现TypeError: fetch不是函数的错误

4
我有一个React Native项目,其中只包含使用新项目创建的示例Jest测试(它们仅检查在iOS和Android上渲染是否正常)。
我的项目在一个组件中使用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 />
  );
});

你应该展示一些代码。这个链接有帮助吗?http://stackoverflow.com/questions/30954899/react-native-fetch-is-not-a-function - Matthias
我发布了使用fetch的代码。我没有使用require,所以我的问题似乎不同。 - Mihai Damian
fetch 是 React Native 自带的,但是 NodeJS 没有(我猜 Jest 是运行在 NodeJS 上的,但我自己从未使用过)。尝试为你的测试添加一个 fetch polyfill。 - Bruno Grieder
1个回答

8
将以下内容添加到您的测试文件中。
import 'isomorphic-fetch';

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接