简体   繁体   中英

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:

在此处输入图片说明

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?

我无法使用您提供的代码对此进行测试,但是安装和导入 npm 模块jest-fetch-mock应该可以解决问题。

Try to keep you mock implementation specific to test cases and if multiple test cases are bound to use the same implementation then wrap them up in a describe block along with a beforeEach call inside it.

This helps in describing mock implementation specific to the scenario being tested.

It is hard to test your implementation with the code you supplied, but let's try switching your mock implementation to something like this:

// This is just dummy data - change its shape in a format that your API renders.
const dummyMoviesData = [
    {title: 'some-tilte-1', body: 'some-1'},
    {title: 'some-tilte-2', body: 'some-2'},
    {title: 'some-tilte-3', body: 'some-3'}
];
global.fetch = jest.fn(() => Promise.resolve(dummyMoviesData));

Now, whenever you movie service API gets called, you may expect the outcome to be of shape of dummyMoviesData and even match it.

So,

expect(outcome).toMatchObject(dummyMoviesData);

or

expect(outcome).toEqual(dummyMoviesData);

should do the trick.

As of October 2020, an approach to resolve the error TypeError: fetch is not function is to include the polyfill for fetch using whatwg-fetch .

The package provides a polyfill for .fetch and is well supported and managed by Github.com employees since 2016. It is advisable to read the caveats to understand if whatwg-fetch is the appropriate solution.

Usage is simple for Babel and es2015+, just add to your file.

import 'whatwg-fetch'`

If you are using with Webpack add the package in the entry configuration option before your application entry point.

entry: ['whatwg-fetch', ...]

You can read the comprehensive documentation at https://github.github.io/fetch/

If you are unfamiliar with WhatWG, learn more about the Web Hypertext Application Technology Working Group on their website .

安装下面的代码片段并将其添加到我的 jest 文件的顶部为我修复了它:

import "isomorphic-fetch"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM