Search code examples
javascriptreactjsreact-nativejestjsbabeljs

Jest and Create-react-app: Cannot use import statement outside a module


I have a React Native application where I have some files with some methods that calls certain endpoints. When I try to run Jest is throwing me an error at a local file that is imported. enter image description here

I have the next package.json:

{
  "name": "appName",
  "version": "1.0.0",
  "description": "some description",
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {},
  "devDependencies": {
    "@babel/core": "^7.14.2",
    "@react-native-community/async-storage": "^1.12.1",
    "@react-native-community/netinfo": "^6.0.0",
    "isomorphic-fetch": "^3.0.0",
    "jest": "^26.6.3",
    "jest-fetch-mock": "^3.0.3"
  },
  "jest": {
    "automock": false,
    "setupFiles": [
      "./jest.setup.js"
    ]
  }
}

And the jest.setup.js file is the following:

import mockRNCNetInfo from '@react-native-community/netinfo/jest/netinfo-mock.js'

jest.mock('@react-native-community/netinfo', () => mockRNCNetInfo)

For the moment, this content is commented, otherwise will throw the same error like in the picture.

I tried to test the same stuff in another project where this @react-native-community/netinfo package wasn't saved in devDependencies but in dependencies and it worked but I am not sure if this is the problem. In this specific project I can't let this package as a dependency, it should be in devDependencies.

I found a lot of issues on this but none of them worked on this case, I don't know what to do anymore. Thank you for your time!


Solution

  • I found this answer on internet and it worked for me with some small add-ons but I will post it here maybe will help someone in future:

    1. install babel-jest, babel-preset-env, @babel/runtime and react (the last one might be possible to be necessary only if some other package requires it)
    2. create .babelrc file in root directory and add:
      {
         "env": {
          "test": {
            "plugins": ["transform-es2015-modules-commonjs"]
          }
        }
      }
    
    1. Run your code and should be good to go