jefflau / jest-fetch-mock

Jest mock for fetch
MIT License
886 stars 117 forks source link

setupJest.js bug #61

Open jimsheen opened 6 years ago

jimsheen commented 6 years ago

Using create-react-app, the below didn't work for me

//setupJest.js or similar file 
global.fetch = require('jest-fetch-mock')

Changed to this:

import fetch from 'jest-fetch-mock'
global.fetch = fetch

Not sure if this just happens for me but may have to consider change in documentation.

Cheers

jefflau commented 6 years ago

What happens when you do the first one?

danactive commented 6 years ago

@jimsheen My guess as to why the require statement doesn't work with your code, is that you cannot mix import and require. Require will work with other requires though.

ananyasen commented 5 years ago

https://github.com/jefflau/jest-fetch-mock/pull/124

benjaminreid commented 5 years ago

The only way I can seem to get it to work is inside the tests directly.

import fetch from "jest-fetch-mock";

beforeAll(() => {
  global.fetch = fetch;
});

Using a setup file and...

import fetch from "jest-fetch-mock"

global.fetch = fetch;

I wonder if it’s something to do with browser: true in my Jest config, here’s the full thing...

module.exports = {
  rootDir: "app",
  moduleNameMapper: {
    "\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
      "<rootDir>/javascript/tests/mocks/file.js",
  },
  setupFiles: [
    "dotenv/config",
    "<rootDir>/javascript/tests/helpers.js",
    "<rootDir>/javascript/tests/patches.js",
    "jest-fetch-mock",
  ],
  setupFilesAfterEnv: [
    "@testing-library/react/cleanup-after-each",
    "@testing-library/jest-dom/extend-expect",
  ],
  moduleDirectories: ["node_modules", "<rootDir>/javascript/"],
  browser: true,
};
viT-1 commented 4 years ago

@benjaminreid Another setup: https://github.com/jefflau/jest-fetch-mock/issues/110#issuecomment-578619105