Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: fetch is not a function in React Native & Jest

I have a React Native project that contains only the sample Jest tests that are created with a new project (they just check if rendering works on iOS and Android).

My project uses fetch for network requests in one of the components. This works fine when I run the app, but when I run the tests they fail with this error message:

TypeError: fetch is not a function.

Anyone knows what's going on?

Here's the part of my code that uses 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);
    });
}}

An the test file:

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 />
  );
});
like image 947
Mihai Damian Avatar asked Mar 10 '23 16:03

Mihai Damian


1 Answers

Add this to your test file.

import 'isomorphic-fetch';
like image 126
pachun Avatar answered Mar 16 '23 13:03

pachun