Friday 9 July 2021

Jest - ReferenceError: __DEV__ is not defined (React Native)

I am trying to get jest to work with a new react-native project. However, when I run npm run test, I get the following error ReferenceError: __DEV__ is not defined. I've looked through countless Github issues and Stack Overflow posts regarding this but none of the suggestions have worked in my case.

Here is my jest.config.js file:

module.exports = {
    transformIgnorePatterns: [
       "node_modules/(?!(react-native|react-native-button|react-native-video)/)"
    ],  
    setupFiles: ['<rootDir>/__tests__/setup.json'],  
}

package.json (notice I added DEV = true inside "jest")

{
  "name": "DigitalSignagePlayer",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@react-native-async-storage/async-storage": "^1.15.5",
    "axios": "^0.21.1",
    "react": "^17.0.1",
    "react-native": "0.64.2",
    "react-native-fs": "^2.18.0",
    "react-native-splash-screen": "^3.2.0",
    "react-native-video": "^5.1.1"
  },
  "devDependencies": {
    "@babel/core": "^7.14.5",
    "@babel/preset-env": "^7.14.7",
    "@babel/runtime": "^7.14.5",
    "@react-native-community/eslint-config": "^2.0.0",
    "babel-jest": "^27.0.2",
    "eslint": "^7.28.0",
    "jest": "^27.0.5",
    "metro-react-native-babel-preset": "^0.66.0",
    "react-test-renderer": "17.0.1"
  },
  "jest": {
    "preset": "react-native",
  }

}

bable.config.js

module.exports = {
  presets: ['module:metro-react-native-babel-preset', '@babel/preset-env'],
  
};

metro.config.js

/**
 * Metro configuration for React Native
 * https://github.com/facebook/react-native
 *
 * @format
 */

module.exports = {
  transformer: {
    getTransformOptions: async () => ({
      transform: {
        experimentalImportSupport: false,
        inlineRequires: true,
      },
    }),
  },
};

I have tried setting globals.DEV = true and global.DEV = true at the top of my test files. I have tried adding setupFiles to jest.config.js which loads a setup.js file that contains global.DEV = true too. I have tried updating jest also. My current version of react-native is:

react-native-cli: 2.0.1
react-native: 0.64.2

I'm also using Metro, not Expo and I initially created the app with react-native-cli.

UPDATE:

setup.json

{
    "globals": { "__DEV__": true } 
}

UPDATE 2:

I changed setup.json to setup.js but I am still getting the same error:

 global.__DEV__ = true


from Jest - ReferenceError: __DEV__ is not defined (React Native)

No comments:

Post a Comment