jest-expo Cannot use import statement outside a module

Please provide the following:

  1. SDK Version: 41.0.1
  2. Platforms(Android/iOS/web/all): Android/iOS

I have tried to follow Testing with Jest - Expo Documentation but when I run npm test I’m getting the following error:

 import React from 'react'
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      3 | import { createStackNavigator } from '@react-navigation/stack'
      4 |
    > 5 | import MainTabsNavigation from './components/MainTabsNavigation'
        | ^
      6 | import ApiCallEdit from './components/ApiCalls/ApiCallEdit'
      7 | import ConditionEdit from './components/Conditions/ConditionEdit'
      8 | import BlockEdit from './components/Blocks/BlockEdit'

      at Runtime._execModule (node_modules/jest-runtime/build/index.js:1157:58)
      at Object.<anonymous> (App.js:5:1)

I believe it has something to do with configuring transformIgnorePatterns but I’m not sure exactly how.

My project code is available here on cleanup-and-pipeline branch.

Thanks in advance for the help.

Ok I think I solved it :sweat_smile:

TLDR: add "transform": {"\\.[jt]sx?$": "babel-jest"}, to package.json under jest config or your jest.config.js.

I got that value from the default value in the Jest docs https://jestjs.io/docs/configuration#transform-objectstring-pathtotransformer–pathtotransformer-object.

It looks like jest-expo will overwrite this to {} if you don’t set it yourself see https://github.com/expo/expo/blob/master/packages/jest-expo/jest-preset.js#L10.

I’m not sure exactly why this is, there may be a reason. But for me this solved my issue.

In my package.json the whole jest bit now looks like:

  "jest": {
    "preset": "jest-expo",
    "transform": {"\\.[jt]sx?$": "babel-jest"},
    "transformIgnorePatterns": [
      "node_modules/(?!(jest-)?react-native|react-clone-referenced-element|@react-native-community|expo(nent)?|@expo(nent)?/.*|react-navigation|@react-navigation/.*|@unimodules/.*|unimodules|sentry-expo|native-base|@sentry/.*)"
    ]
  },

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.