javascript - 类型错误 : fetch is not a function in React Native & Jest

标签 javascript react-native jestjs

我有一个 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 />
  );
});

最佳答案

将此添加到您的测试文件。

import 'isomorphic-fetch';

关于javascript - 类型错误 : fetch is not a function in React Native & Jest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42649036/

相关文章:

javascript - Touchend 事件,回到 touchstart 状态动画

react-native - 您可以从 React Native 调试器重新加载 React Native 应用程序吗?

javascript - Jest 测试失败

reactjs - 如何测试子组件是否已呈现?

javascript - 根据条件从选择列表中删除值

javascript - 如何使用 jQuery.ajax 和 FormData 上传文件

javascript - 如何在 switch 语句中执行特定情况下的多个代码块?

javascript - 导入文件的变量未更新

react-native - 如何在 React Native 中通过 Paypal 实现汇款?

javascript - Jest spyOn 函数调用