jest: Fetch do not work on Jest

Do you want to request a feature or report a bug? bug

What is the current behavior? fetch do not make the request to the server

test example:

describe('app', () => {
  it('fetch correctly', async () => {
    const response = await fetch('http://localhost:5000/graphql')
    const data = await response.text();

    expect(data).not.toBe(null);
  });
});

This test is inside a react native project, I have a very long timeout

jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;.

I’m trying to implement integration tests using a real GraphQL backend (following the ideas of https://github.com/facebook/relay/issues/1281)

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal repository on GitHub that we can npm install and npm test.

What is the expected behavior? fetch should make the request to the server

Run Jest again with --debug and provide the full configuration it prints. Please mention your node and npm version and operating system.

jest version = 17.0.0
test framework = jasmine2
config = {
  "haste": {
    "defaultPlatform": "ios",
    "platforms": [
      "android",
      "ios"
    ],
    "providesModuleNodeModules": [
      "react",
      "react-native"
    ]
  },
  "moduleNameMapper": [
    [
      "^image![a-zA-Z0-9$_-]+$",
      "GlobalImageStub"
    ],
    [
      "^[./a-zA-Z0-9$_-]+\\.(bmp|gif|jpg|jpeg|png|psd|svg|webp)$",
      "RelativeImageStub"
    ]
  ],
  "modulePathIgnorePatterns": [
    "app/node_modules/react-native/Libraries/react-native/",
    "app/node_modules/react-native/packager/"
  ],
  "transformIgnorePatterns": [
    "node_modules/(?!react-native|tcomb-form-native|react-native-localization|@exponent/react-native-action-sheet|@exponent/ex-navigation|@exponent/react-native-touchable-native-feedback-safe|rnrf-relay-renderer|react-clone-referenced-element|react-native-looped-carousel|rn-splash-screen)"
  ],
  "setupFiles": [
    "app/node_modules/babel-polyfill/lib/index.js",
    "app/node_modules/jest-react-native/build/setup.js"
  ],
  "testEnvironment": "app/node_modules/jest-environment-node/build/index.js",
  "snapshotSerializers": [
    "app/node_modules/jest-html"
  ],
  "preset": "jest-react-native",
  "unmockedModulePathPatterns": [
    "app/node_modules/fbjs-scripts/",
    "app/node_modules/fbjs/node_modules/core-js/",
    "app/node_modules/fbjs/node_modules/promise/",
    "app/node_modules/fbjs/lib/(?!(ErrorUtils.js$|fetch.js$|fetchWithRetries.js$))",
    "app/node_modules/object-assign/",
    "app/node_modules/react/",
    "app/node_modules/react-addons-test-utils/",
    "app/node_modules/react-dom/",
    "app/node_modules/react-static-container/",
    "app/node_modules/react-relay/",
    "app/node_modules/event-target-shim",
    "app/node_modules/whatwg-fetch"
  ],
  "verbose": true,
  "moduleFileExtensions": [
    "js",
    "json",
    "es6",
    "ios.js"
  ],
  "rootDir": "app",
  "name": "-Users-sibelius-Dev-rturk-brandlovers-reactnative",
  "testRunner": "app/node_modules/jest-jasmine2/build/index.js",
  "transform": [
    [
      "^.+\\.jsx?$",
      "app/node_modules/babel-jest/build/index.js"
    ]
  ],
  "usesBabelJest": true,
  "automock": false,
  "bail": false,
  "browser": false,
  "cacheDirectory": "/var/folders/n_/30jh5m816yzg3_cftvg647j40000gn/T/jest",
  "coveragePathIgnorePatterns": [
    "/node_modules/"
  ],
  "coverageReporters": [
    "json",
    "text",
    "lcov",
    "clover"
  ],
  "expand": false,
  "globals": {},
  "mocksPattern": "__mocks__",
  "moduleDirectories": [
    "node_modules"
  ],
  "noStackTrace": false,
  "notify": false,
  "resetMocks": false,
  "resetModules": false,
  "testPathDirs": [
    "app"
  ],
  "testPathIgnorePatterns": [
    "/node_modules/"
  ],
  "testRegex": "(/__tests__/.*|\\.(test|spec))\\.jsx?$",
  "testURL": "about:blank",
  "timers": "real",
  "useStderr": false,
  "watch": false,
  "cache": true,
  "watchman": true,
  "testcheckOptions": {
    "times": 100,
    "maxSize": 200
  }
}

node 6.9.1 mac os x sierra

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 7
  • Comments: 18 (2 by maintainers)

Most upvoted comments

For people passing by, simplest working solution:

function mockFetch(data) {
  return jest.fn().mockImplementation(() =>
    Promise.resolve({
      ok: true,
      json: () => data
    })
  );
}

test('fetchPerson()', async () => {
  fetch = mockFetch(someJson); // or window.fetch

  const person = await fetchPerson('whatever id');
  expect(person).toEqual(someJson);

  // Make sure fetch has been called exactly once
  expect(fetch).toHaveBeenCalledTimes(1);
});

when testing this simple function:

function fetchPerson(id) {
  const response = await fetch(`${BASE_URL}/people/${id}`);
  if (!response.ok) throw new Error(response.statusText);
  const data = await response.json();
  // Some operations on data if needed...
  return person;
}

Jest configuration:

// File jest.setup.js
import 'whatwg-fetch';
// File jest.config.js
module.exports = {
  setupFiles: ['./jest.setup.js'],
};

(because Jest uses Node.js and Node.js does not come with fetch => specific to web browsers)

Real life simple example: https://github.com/tkrotoff/MarvelHeroes

@tkrotoff whatwg-fetch didn’t work for me, isomorphic-fetch did

fetch is not available in Node, which is where Jest is running your tests. Is it an experimental browser technology.

You will need to polyfill the behaviour if you want to make actual http calls, or mock fetch to simulate network requests.

it works on setupFiles and I have to polyfill XMLHttpRequest (https://github.com/ykzts/node-xmlhttprequest)

tks

Exactly! Check out whatwg-fetch.

Figured it out. Added a setupJest.js file to the setupFiles section of my package.json. Then added this to setupJest.js global.XMLHttpRequest = require('w3c-xmlhttprequest').XMLHttpRequest;

I didn’t really wanted to mock on a specific test and node-fetch came through brilliantly for me.

Is isomorphic-fetch not in the Jest any more?

Weirdly, neither of the polyfills repacing XMLHttpResponse in the fixes above seemed to work – I had to replace fetch entirely, by including require("isomorphic-fetch"); in the setupFiles as described above.