Skip to content
Advertisement

Jest TypeError: fetch is not a function

I have the following Jest test code to test a fetch to an endpoint:

import MovieApiService from 'services/MovieApiService';
import movies from '../constants/movies';

describe('MovieApiService', () => {

  test('if jest work correctly', () => {
    expect(true).toBe(true);
  });

  test('get an array of popular movies', () => {
    global.fetch = jest.mock('../mocks/movies');
    const movieApiService = new MovieApiService();
    return movieApiService.getPopularMovies()
      .then(data => expect(data).toBe(movies));
  });
});

But I am getting:

Enter image description here

I know that the movieApiService.getPopularMovies() is a JavaScript fetch request, but Node.js does not have the fetch API, so how I can I make this test to work using Jest?

Advertisement

Answer

I can’t test this with the code you supply, but installing and importing the npm module jest-fetch-mock should do the trick.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement