Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

jest fails with @react-native/polyfills/error-guard.js after upgrade to RN 0.64.0 and react 17.0.1 #152

Open
sammysium opened this issue Apr 18, 2021 · 49 comments

Comments

@sammysium
Copy link

Environment

System:
OS: Linux 5.4 Ubuntu 18.04.5 LTS (Bionic Beaver)
CPU: (8) x64 Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz
Memory: 1.29 GB / 15.52 GB
Shell: 4.4.20 - /bin/bash
Binaries:
Node: 14.5.0 - ~/.nvm/versions/node/v14.5.0/bin/node
Yarn: 1.22.5 - /usr/bin/yarn
npm: 6.14.9 - ~/.nvm/versions/node/v14.5.0/bin/npm
Watchman: 20200920.192359.0 - /usr/local/bin/watchman
SDKs:
Android SDK:
API Levels: 19, 24, 25, 27, 28, 29, 30
Build Tools: 28.0.3, 29.0.2, 29.0.3, 30.0.0
System Images: android-22 | Google APIs Intel x86 Atom, android-25 | Google APIs Intel x86 Atom, android-28 | Google Play Intel x86 Atom
Android NDK: Not Found
IDEs:
Android Studio: Not Found
Languages:
Java: 11.0.10 - /usr/bin/javac
npmPackages:
@react-native-community/cli: Not Found
react: 17.0.1 => 17.0.1
react-native: 0.64.0 => 0.64.0
npmGlobalPackages:
react-native: Not Found

Things I’ve done to figure out my issue

did react-native upgrade which upgraded the appplication

Upgrading version

react-native 0.64.0
react 17.0.1

Description

After the upgrade, I did yarn test but all tests fail with error:

/node_modules/@react-native/polyfills/error-guard.js:14
    type ErrorHandler = (error: mixed, isFatal: boolean) => void;
         ^^^^^^^^^^^^

    SyntaxError: Unexpected identifier
@kumarparth380
Copy link

Add @react-native to your transformIgnorePatterns like this to your jest.config.js :

transformIgnorePatterns: [
    "/node_modules/(?!(@react-native|react-native)/).*/"
  ]

Also add the preset something like this in jest.config.js:

preset: "react-native",
setupFilesAfterEnv: ["@testing-library/jest-native/extend-expect"]

Check out for the libraries and update them accordingly to meet latest react version.

@tbeech
Copy link

tbeech commented May 12, 2021

Same issue here, but I get this failure when using typescript.

@shehzadq
Copy link

/app/node_modules/@react-native/polyfills/error-guard.js:14
    type ErrorHandler = (error: mixed, isFatal: boolean) => void;
         ^^^^^^^^^^^^
facing same issue: 

    SyntaxError: Unexpected identifier

      at Runtime.createScriptFromCode (../../node_modules/jest-runtime/build/index.js:1350:14)
      at Object.<anonymous> (../../node_modules/react-native/jest/setup.js:439:6)

@cinemanja
Copy link

Any updates on this? Still facing the same issue.

@nadav2051
Copy link

Same here, with RN 0.63.3

@wwwmaster
Copy link

Try to create babel.config.js with next content

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

@kopax-polyconseil
Copy link

Same here after upgrading ts-jest, jest, and react-native to latest.

@rholliger
Copy link

Adding the @react-native to the transformIgnorePatterns in the jest config solved it for me

transformIgnorePatterns: [
    "/node_modules/(?!(@react-native|react-native)/).*/"
]

@dorthwein
Copy link

@rholliger adding that ignore causes a Cannot find module './Libraries/Utilities/warnOnce' error :(

@pastean
Copy link

pastean commented Jun 27, 2021

doesn't work for me either, tried different patterns similar to the one posted by @rholliger . Still debugging, will keep you updated if I find something

@rholliger
Copy link

@rholliger adding that ignore causes a Cannot find module './Libraries/Utilities/warnOnce' error :(

Have you tried this already: facebook/react-native#23943 (comment)

@interhub
Copy link

interhub commented Jul 2, 2021

I found out the solve ✅
You should remove react-native from transformIgnorePatterns regexp array !

transformIgnorePatterns: [
    '<rootDir>/node_modules/(react-clone-referenced-element|@react-native-community|react-navigation|@react-navigation/.*|@unimodules/.*|native-base|react-native-code-push)',
  ],

as Problem was in type define into js file which dont transforming because we was disable it. React native 64 developers add type ErrorHandler and we need it transform with ts-loader

my self jest.config.js file in root (example)

const {defaults: tsjPreset} = require('ts-jest/presets');

module.exports = {
  ...tsjPreset,
  preset: 'react-native',
  globals: {
    'ts-jest': {
      babelConfig: true,
    },
  },
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/$1',
    '^~/(.*)$': '<rootDir>/$1',
    '\\.svg': '<rootDir>/__mocks__/svgMock.js',
    'react-native-code-push': '<rootDir>/__mocks__/react-native-code-push.js',
    '@react-navigation': '<rootDir>/__mocks__/@react-navigation.js',
  },
  testRegex: '(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$',
  transformIgnorePatterns: [
    '<rootDir>/node_modules/(react-clone-referenced-element|@react-native-community|react-navigation|@react-navigation/.*|@unimodules/.*|native-base|react-native-code-push)',
  ],
  testPathIgnorePatterns: ['<rootDir>/node_modules/', '\\.snap$'],
  cacheDirectory: '.jest/cache',
  testEnvironment: 'jsdom',
  setupFiles: ['<rootDir>/__mocks__/mock-setup.js'],
};

@nikhilk1993
Copy link

nikhilk1993 commented Jul 13, 2021

any update on this? still test cases breaking on RN version 0.64.2

@johnhaup
Copy link

Try renaming your Babel config from .babelrc to babel.config.js

srkela added a commit to srkela/GitAPI that referenced this issue Jul 20, 2021
reason: unable to run jest in new RN version
reference: react-native-community/upgrade-support#152
@cs-manughian
Copy link

I found out the solve ✅
You should remove react-native from transformIgnorePatterns regexp array !

transformIgnorePatterns: [
    '<rootDir>/node_modules/(react-clone-referenced-element|@react-native-community|react-navigation|@react-navigation/.*|@unimodules/.*|native-base|react-native-code-push)',
  ],

as Problem was in type define into js file which dont transforming because we was disable it. React native 64 developers add type ErrorHandler and we need it transform with ts-loader

my self jest.config.js file in root (example)

const {defaults: tsjPreset} = require('ts-jest/presets');

module.exports = {
  ...tsjPreset,
  preset: 'react-native',
  globals: {
    'ts-jest': {
      babelConfig: true,
    },
  },
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/$1',
    '^~/(.*)$': '<rootDir>/$1',
    '\\.svg': '<rootDir>/__mocks__/svgMock.js',
    'react-native-code-push': '<rootDir>/__mocks__/react-native-code-push.js',
    '@react-navigation': '<rootDir>/__mocks__/@react-navigation.js',
  },
  testRegex: '(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$',
  transformIgnorePatterns: [
    '<rootDir>/node_modules/(react-clone-referenced-element|@react-native-community|react-navigation|@react-navigation/.*|@unimodules/.*|native-base|react-native-code-push)',
  ],
  testPathIgnorePatterns: ['<rootDir>/node_modules/', '\\.snap$'],
  cacheDirectory: '.jest/cache',
  testEnvironment: 'jsdom',
  setupFiles: ['<rootDir>/__mocks__/mock-setup.js'],
};

I can confirm this transform works for me!

@rickyalmeidadev
Copy link

Try renaming your Babel config from .babelrc to babel.config.js

Solved my problem. Thanks, @johnhaup!

@Eandalf
Copy link

Eandalf commented Aug 16, 2021

I found out the solve ✅
You should remove react-native from transformIgnorePatterns regexp array !

transformIgnorePatterns: [
    '<rootDir>/node_modules/(react-clone-referenced-element|@react-native-community|react-navigation|@react-navigation/.*|@unimodules/.*|native-base|react-native-code-push)',
  ],

as Problem was in type define into js file which dont transforming because we was disable it. React native 64 developers add type ErrorHandler and we need it transform with ts-loader

my self jest.config.js file in root (example)

const {defaults: tsjPreset} = require('ts-jest/presets');

module.exports = {
  ...tsjPreset,
  preset: 'react-native',
  globals: {
    'ts-jest': {
      babelConfig: true,
    },
  },
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/$1',
    '^~/(.*)$': '<rootDir>/$1',
    '\\.svg': '<rootDir>/__mocks__/svgMock.js',
    'react-native-code-push': '<rootDir>/__mocks__/react-native-code-push.js',
    '@react-navigation': '<rootDir>/__mocks__/@react-navigation.js',
  },
  testRegex: '(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$',
  transformIgnorePatterns: [
    '<rootDir>/node_modules/(react-clone-referenced-element|@react-native-community|react-navigation|@react-navigation/.*|@unimodules/.*|native-base|react-native-code-push)',
  ],
  testPathIgnorePatterns: ['<rootDir>/node_modules/', '\\.snap$'],
  cacheDirectory: '.jest/cache',
  testEnvironment: 'jsdom',
  setupFiles: ['<rootDir>/__mocks__/mock-setup.js'],
};

This one solved my problem. Great thanks to @interhub.

For my case,

  globals: {
    'ts-jest': {
      tsconfig: 'tsconfig.spec.json', // as specified by ts-jest
      babelConfig: true,
    },
  },
  // ...
  transformIgnorePatterns: [],

does the trick.

Even if I put "/node_modules/(?!(@react-native|react-native)/).*/" in transformIgnorePatterns, I still got type ErrorHandler ... SyntaxError: Unexpected identifier. After digging in react-native's jest-preset.js (source code), the line ("/node_modules/(?!(@react-native|react-native)/).*/") was already there. There must be something else going wrong. Then, I saw @interhub 's line babelConfig: true. Suddenly, I remembered some stuff written by react-native contributors, they stated that they used Babel to transpile Typescript instead of compiling Typescript code using tsc. Then, if we could build the app, but the tests failed, how about letting Babel to take care of the mess? (No offense, I am more used to Typescript than Flow.) Then, it works. After using this approach, aside from solving the type in .js problem with jest, no need to repeat the path alias set in babel.config.js in jest.config.js - moduleNameMapper again, those non-relative path imports will be taken care by Babel (I am using babel-plugin-module-resolver).

I am using react-native@0.64.2, jest@^26.6.3, ts-jest@^26.5.6. The following is my jest.config.js.

// jest.config.js
module.exports = {
  preset: 'react-native',
  globals: {
    'ts-jest': {
      tsconfig: 'tsconfig.spec.json',
      babelConfig: true,
    },
  },
  moduleFileExtensions: [
    'ts',
    'tsx',
    'js',
    'jsx',
    'json',
    'node',
  ],
  transform: {
    '^.+\\.(js|jsx)$': 'babel-jest',
    '^.+\\.(ts|tsx)$': 'ts-jest',
  },
  // This line should be kept even with nothing to be ignored, otherwise the transform will not take place.
  // Not quite sure about the reason.
  transformIgnorePatterns: [],
  testRegex: '(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$',
  testPathIgnorePatterns: [
    '<rootDir>/node_modules/',
    '\\.snap$',
  ],
  cacheDirectory: '.jest/cache',
};

For tsconfig.spec.json, please refer to Using with React Native | ts-jest.

@nwalters512
Copy link

Other folks in this discussion have mentioned TypeScript as the culprit, but these are actually Flow types. It seems like react-native is now shipping untranspiled Flow code for some reason. To work around this, I installed @babel/plugin-transform-flow-strip-types and added it to my Babel config. Combined with the default transformIgnorePatterns value from the React Native Jest preset, my tests are now able to run again.

I would encourage the maintainers to ship code that does not use untranspiled Flow, as that breaks the assumptions a lot of JavaScript tooling makes.

@AlexJWayne
Copy link

I'm having a hell of time with this.

When I get what should be the right transformIgnorePatterns the error changes to this:

SyntaxError: /path/to/my-mono-repo/apps/mobile-v2/node_modules/react-native/Libraries/polyfills/error-guard.js: Unexpected token (45:12)

      43 |         _globalHandler && _globalHandler(error, true);
      44 |     }
    > 45 | } < mixed > , TOut;
         |             ^
      46 |  > (fun);
      47 | Fn < TArgs, TOut > ,
      48 |     context ?  :  ? mixed : ,

      at Parser._raise (../../node_modules/@babel/parser/lib/index.js:788:17)
      at Parser.raiseWithData (../../node_modules/@babel/parser/lib/index.js:781:17)
      at Parser.raise (../../node_modules/@babel/parser/lib/index.js:742:17)
      at Parser.unexpected (../../node_modules/@babel/parser/lib/index.js:9929:16)
      at Parser.parseExprAtom (../../node_modules/@babel/parser/lib/index.js:11349:20)
      at Parser.parseExprSubscripts (../../node_modules/@babel/parser/lib/index.js:10914:23)
      at Parser.parseUpdate (../../node_modules/@babel/parser/lib/index.js:10894:21)
      at Parser.parseMaybeUnary (../../node_modules/@babel/parser/lib/index.js:10872:23)
      at Parser.parseExprOpBaseRightExpr (../../node_modules/@babel/parser/lib/index.js:10819:34)
      at Parser.parseExprOpRightExpr (../../node_modules/@babel/parser/lib/index.js:10812:21)

I've added "plugins": ["@babel/plugin-transform-flow-strip-types"] to my babel.config.js also seems to have no effect.

Related issue with a repository that I can't make work here: JacopoPatroclo/nx-react-native-expo#21

@MrAdex77
Copy link

MrAdex77 commented Oct 24, 2021

Same error by me and i just created new project with typescript and cant run even initial test...


    E:\Studia\ReactNative\ComparePrices\node_modules\react-native\Libraries\vendor\core\ErrorUtils.js:11
    import type {ErrorUtilsT} from '@react-native/polyfills/error-guard';
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (node_modules/react-native/jest/setup.js:37:3)

My config:
Babel.config.js

// eslint-disable-next-line no-undef
module.exports = {
  presets: ["module:metro-react-native-babel-preset", "@babel/preset-typescript"],
  plugins: [
    "module:react-native-dotenv",
    "@babel/plugin-proposal-export-namespace-from",
    [
      "module-resolver",
      {
        root: ["./"],
        alias: { "^~(.+)": "./src/\\1" },
        extensions: [".ios.js", ".android.js", ".js", ".ts", ".tsx", ".json"],
      },
    ],
  ],
};

jest.config.ts

export default {
  clearMocks: true,

  globals: {
    "ts-jest": {
      tsconfig: "tsconfig.spec.json", // as specified by ts-jest
      babelConfig: true,
    },
  },

  moduleFileExtensions: ["js", "jsx", "ts", "tsx", "json", "node"],

  moduleNameMapper: {
    "^.+.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub",
  },

  preset: "react-native",

  testEnvironment: "jsdom",

  transform: {
    "^.+\\.jsx$": "babel-jest",
    "^.+\\.tsx?$": "ts-jest",
    ".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub",
  },

  transformIgnorePatterns: ["node_modules/(?!(@react-native)/)"],

  verbose: true,
};

@huanguolin
Copy link

huanguolin commented Nov 16, 2021

Same error
`
C:\SourceCode\leyserkids-kp-rn\node_modules\react-native-config\index.js:6
import { NativeModules } from 'react-native';
^^^^^^

SyntaxError: Cannot use import statement outside a module

  1 | // eslint-disable-next-line no-restricted-imports
> 2 | import Config from 'react-native-config';
    | ^
  3 |
  4 | export enum Env {
  5 |     dev = 'dev',

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
  at Object.<anonymous> (config/config.ts:2:1)

`

@huanguolin
Copy link

I fixed it by add this:
"transformIgnorePatterns": [ "/node_modules/(?!(@react-native|react-native)).*/" ]

@MortezaHeydari97
Copy link

MortezaHeydari97 commented Dec 9, 2021

presets: ['module:metro-react-native-babel-preset'],

It's working for me.
Because I was moved metro config (presets: ['module:metro-react-native-babel-preset']) to .babelrc and it was not working.
Now I created an babel.config.js and put that into it and test working correctly.

@CoSNaYe
Copy link

CoSNaYe commented Oct 3, 2022

[update]
I found using jest: "^27" works.
Just use preset: react-native and don't need to override transform nor transformIgnorePatterns


still not working 😔 I've tried all methods mentioned above.

Here's the repo which is just a new RN project.
If possible, please someone to help. Thanks!

    "react": "18.1.0",
    "react-native": "0.70.1"
    "@babel/core": "^7.19.3",
    "@testing-library/jest-native": "^5.0.0",
    "@testing-library/react-native": "^11.2.0",
    "@types/jest": "^29.1.1",
    "babel-jest": "^29.1.2",
    "babel-preset-expo": "^9.2.0",
    "detox": "^19.12.5",
    "jest": "^29.1.2",
    "metro-react-native-babel-preset": "^0.72.1",
    "ts-jest": "^29.0.3",
    "typescript": "^4.8.4"

@matthew-dean
Copy link

So wait, you can only use ts-jest? You can't use SWC because they use Flow, which then requires Babel?

@johnmccants002
Copy link

What worked for me.

My error

node_modules/@react-native/polyfills/error-guard.js:14
type ErrorHandler = (error: mixed, isFatal: boolean) => void;
^^^^^^^^^^^^

SyntaxError: Unexpected identifier

jest.config.ts file below. I added @react-native to it

import { Config } from "@jest/types";

// By default, all files inside `node_modules` are not transformed. But some 3rd party
// modules are published as untranspiled, Jest will not understand the code in these modules.
// To overcome this, exclude these modules in the ignore pattern.
const untranspiledModulePatterns = [
  "(jest-)?react-native",
  "@react-native-community",
  "expo(nent)?",
  "@expo(nent)?/.*",
  "react-navigation",
  "@react-navigation/.*",
  "@unimodules/.*",
  "unimodules",
  "sentry-expo",
  "native-base",
  "react-native-svg",
  "@react-native*" <--- This line did it for me
];

const config: Config.InitialOptions = {
  preset: "jest-expo",
  transformIgnorePatterns: [
    `node_modules/(?!${untranspiledModulePatterns.join("|")})`,
  ],
  moduleFileExtensions: ["ts", "tsx", "js", "jsx"],
};

export default config;

@supmanyu
Copy link

Facing the same problem on a non-typescript project, react-native@0.64.3

  • already have babel.config.js instead of .babelrc
  • tried removing transformIgnorePatterns as well changing the values based on the answers given above
  • changing react-native plugin to jest-expo
  • tried changing babel preset to @babel/plugin-transform-flow-strip-types (doesn't seem to do anything)
  • updating/downgrading libraries to the versions given in a freshly init bare app

@Osvaldo111
Copy link

Try renaming your Babel config from .babelrc to babel.config.js

After debugging I found that renaming the file from .babelrc to babel.config.js worked for me. Without using transformIgnorePatterns with the jest.config.js. The following config is what works with "JS" and "JSX" files.

babel.config.js

module.exports = { 
    presets: ["module:metro-react-native-babel-preset"],
}

jest.confg.js

module.exports = {
    preset: 'react-native',
};

superstar1205 added a commit to superstar1205/Map-ReactNative that referenced this issue Dec 26, 2022
babel config is needed to run jest tests after upgrading react-native.
See: react-native-community/upgrade-support#152
Also, it's part of most libraries either way.
@otech47
Copy link

otech47 commented Mar 19, 2023

I was able to fix this

starting with a jest.config.js file that was producing the error:

/** @type {import('@jest/types').Config.InitialOptions} */
module.exports = {
    preset: 'react-native',
    rootDir: '..',
    testMatch: ['<rootDir>/**/*.test.ts'],
    testPathIgnorePatterns: ['<rootDir>/e2e/*'],
    moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
}

none of the answers above worked for me. no variation of transformIgnorePatterns worked either, jest still went in and tried to transpile the bad polyfill file no matter what.

i figured out my babel.config.js file wasn't getting picked up automatically... since I added a console.log and it wasn't running

adding this transform fixed it:

/** @type {import('@jest/types').Config.InitialOptions} */
module.exports = {
    preset: 'react-native',
    rootDir: '..',
    testMatch: ['<rootDir>/**/*.test.ts'],
    testPathIgnorePatterns: ['<rootDir>/e2e/*'],
    moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
    transform: {
        '^.+\\.(js|jsx|ts|tsx)$': [
            'babel-jest',
            { configFile: './babel.config.js' }, // <- cannot use rootDir here
        ],
    },
}

also note that the configFile must be a relative path from your current directory that you are running jest from. rootDir will not be respected

this was my babel.config.js... no need for @babel/plugin-transform-flow-strip-types either...

module.exports = function (api) {
    const presets = ['module:metro-react-native-babel-preset']
    const plugins = [
        [
            'react-native-reanimated/plugin',
            {
                globals: ['__scanCodes'],
            },
        ],
    ]

    ...
    
    return {
        presets,
        plugins,
    }
}

anthony0506 added a commit to anthony0506/react-native-maps that referenced this issue Mar 19, 2023
babel config is needed to run jest tests after upgrading react-native.
See: react-native-community/upgrade-support#152
Also, it's part of most libraries either way.
@RyanMurphyMobi
Copy link

RyanMurphyMobi commented Mar 22, 2023

Does anyone have a fix for

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
 • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation

Details:

C:\Users\Ryan\android\node_modules\@react-native\polyfills\error-guard.js:44
} < mixed > , TOut;
            ^

SyntaxError: Unexpected token ','

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1495:14)
  at Object.<anonymous> (node_modules/react-native/jest/setup.js:16:6)

I have tried everything in this form and nothing can get me past this error.

My current jest config is:

"jest": { "preset": "react-native", "transform": { "^.+\\.(t|j)sx?$": "ts-jest", "^.+\\.(ts|tsx)?$": "ts-jest", "^.+\\.(js|jsx)$": "babel-jest", "^.+/((@)?react-native)/.+\\.(js|jsx)$": "babel-jest" }, "transformIgnorePatterns": [ "node_modules/(?!(@react-native(-.*)?|@react-native(-community)?)/)", "node_modules/(?!(@react-native|react-native|@react-native*)/).*/" ], "testPathIgnorePatterns": [ "./e2e" ] }

and my babel.config.js includes:

module.exports = { presets: ["module:metro-react-native-babel-preset"] };

salah-ghanim pushed a commit to GET-A-WAY/react-native-maps that referenced this issue Apr 5, 2023
babel config is needed to run jest tests after upgrading react-native.
See: react-native-community/upgrade-support#152
Also, it's part of most libraries either way.
@thevikas
Copy link

still getting this same issue. for three days now. Have tried anything and everything:

Jest Error

Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /xx/mobile/node_modules/@react-native/polyfills/error-guard.js:14
    type ErrorHandler = (error: mixed, isFatal: boolean) => void;
         ^^^^^^^^^^^^

    SyntaxError: Unexpected identifier

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (node_modules/react-native/jest/setup.js:16:6)


jest.config.js

module.exports = {
    //preset: '@testing-library/react-native', //react-native',
    preset: 'react-native',
    globals: {
        __DEV__: true
    },
    collectCoverage: false,
    collectCoverageFrom: [
        '**/src/**/*.{js,jsx,ts,tsx}',
        '!**/src/**/style.js',
        '!**/src/**/index.js',
        '!**/src/theme/**',
        '!**/android/**',
        '!**/ios/**',
        '!**/node_modules/**',
        '!**/scripts/**',
        '!**/__test__/**'
    ],
    //"snapshotSerializers": [],
    //@see jenkins setting up
    //https://medium.com/@elisegev/running-tests-and-creating-code-coverage-reports-for-react-nodejs-project-continuously-with-60312b6a2dd0
    coverageDirectory: "./output",
    coverageReporters: [
        "text",
        "html",
        "cobertura"
    ],
    coveragePathIgnorePatterns: [
        "/node_modules/",
        "/jest"
    ],
    moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
    moduleNameMapper: {
        '\\.(css|less)$': 'identity-obj-proxy',
        '^(.+)\\.(jpg|jpeg|gif|png|mp4|mkv|avi|webm|swf|wav|mid)$': 'jest-static-stubs/$2'
    },
    reporters: [
        "default",
        ["jest-junit", {
            "suiteName": "jest tests",
            "outputDirectory": "./output",
            "outputName": "junit.xml",
            "classNameTemplate": "{classname}-{title}",
            "titleTemplate": "{classname}-{title}",
            "ancestorSeparator": " › ",
            "usePathForSuiteName": "true"
        }
        ]
    ],
    restoreMocks: true,
    setupFiles: [
        "./node_modules/react-native-gesture-handler/jestSetup.js",
        "./jest/mock.js"
        //"<rootDir>/jest/setup.js"
    ],
    setupFilesAfterEnv: ["@testing-library/jest-native/extend-expect"],
    testMatch: [
        "<rootDir>/src/**/*.test.js"
    ],
    testPathIgnorePatterns: ["/node_modules/", "e2e/", "__mocks__/"],
    testEnvironmentOptions: { url: 'http://localhost/' },
    //transform: {
    //    //"^.+\\.(js|jsx)$": "<rootDir>/jest.preprocessor.js"
    //},
    transform: {
        '^.+\\.(js|jsx|ts|tsx)$': [
            'babel-jest',
            { configFile: './babel.config.js' }, // <- cannot use rootDir here
        ],
    },
    transformIgnorePatterns: [
        "/node_modules/(?!(jest-)?@codler)",
        "/node_modules/(?!(@react-native|react-native)/)",
        'node_modules/(?!(jest-)?@?react-native|@react-native-community|@react-navigation|react-native-vector-icons|native-base.*)'
    ],
    verbose: true    
}

System

System:
    OS: Linux 5.15 Ubuntu 20.04.6 LTS (Focal Fossa)
    CPU: (12) x64 AMD Ryzen 5 3600 6-Core Processor
    Memory: 57.18 GB / 62.71 GB
    Shell: 5.8 - /usr/bin/zsh
  Binaries:
    Node: 16.20.0 - ~/.nvm/versions/node/v16.20.0/bin/node
    Yarn: 1.22.19 - /usr/bin/yarn
    npm: 8.19.4 - ~/.nvm/versions/node/v16.20.0/bin/npm
    Watchman: Not Found
  SDKs:
    Android SDK:
      API Levels: 23, 25, 26, 27, 28, 31, 32, 33, 33
      Build Tools: 27.0.3, 28.0.3, 30.0.2, 30.0.3, 31.0.0, 33.0.0, 33.0.1, 33.0.2, 34.0.0, 34.0.0
      System Images: android-28 | Google APIs Intel x86 Atom_64, android-30 | Google APIs Intel x86 Atom_64, android-30 | Google Play Intel x86 Atom
      Android NDK: Not Found
  IDEs:
    Android Studio: Not Found
  Languages:
    Java: 11.0.18 - /usr/bin/javac
  npmPackages:
    @react-native-community/cli: Not Found
    react: 16.13.1 => 16.13.1 
    react-native: 0.64.4 => 0.64.4 
  npmGlobalPackages:
    *react-native*: Not Found

package.json

"devDependencies": {
        "@babel/core": "7.12.10",
        "@babel/runtime": "7.12.5",
        "@react-native-community/eslint-config": "^3.2.0",
        "@testing-library/jest-native": "^5.4.2",
        "@testing-library/react-native": "^12.0.1",
        "@types/jest": "^29.5.1",
        "auto-changelog": "^2.4.0",
        "babel-jest": "^29.5.0",
        "detox": "^20.6.0",
        "eslint": "6.8.0",
        "fetch-mock": "^9.11.0",
        "jest": "^27",
        "jest-extended": "^3.2.4",
        "jest-json-schema": "^6.1.0",
        "jest-junit": "^15.0.0",
        "jest-static-stubs": "^0.0.1",
        "metro-react-native-babel-preset": "0.59.0",
        "pre-commit": "^1.2.2",
        "prettier": "^2.8.7",
        "react-test-renderer": "16.13.1",
        "redux-logger": "^3.0.6",
        "redux-mock-store": "^1.5.4",
        "release-it": "^15.10.1",
        "ts-jest": "^29.1.0",
        "typescript": "^5.0.4"
    }

babel.config.js

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

johney6767 pushed a commit to johney6767/Map-ReactNative that referenced this issue May 31, 2023
babel config is needed to run jest tests after upgrading react-native.
See: react-native-community/upgrade-support#152
Also, it's part of most libraries either way.
@earonesty
Copy link

earonesty commented Jun 16, 2023

not using typescript, not using babel, have no babel config, have no tsconfig... only using this file:

{
  "preset": "react-native",
}

doesn't work, same issue.

"react-native": "^0.71"
"jest": "29.5.0"

feel like it's not transforming files it needs to...

@JFGHT
Copy link

JFGHT commented Jul 18, 2023

The solution that worked for me:

babel.config.js

module.exports = api => {
  return {
    presets: ['module:metro-react-native-babel-preset'],
    ...(api.env('test')
      ? {
          plugins: [
            '@babel/plugin-proposal-class-properties',
            '@babel/plugin-transform-private-methods',
          ],
        }
      : {}),
  };
};

@johnnyrwest
Copy link

Super weird, but I am working on upgrading a legacy RN application (0.68.5 => 0.71.1) and running into this issue. We are in a monorepo with our node backend, so lots of setup and config files.

Long short, our react native project dir (/mobile) uses a src dir, and while the react native project root has a babel.config.js and a jest.config.js, our src dir also has a jest.config.ts. Updating that mobile/src/jest.config.ts and adding a mobile/src/babel.config.js got the tests running again.

Definitely looks like an opportunity to clean some things up, but also glad to see some progress.

@elenitaex5
Copy link

I had my project with EXPO and detox configuration still... I had this error too, but looking for a solution here I fix my code.
Including config in package Json I had another error:

Class private methods are not enabled. Please add @babel/plugin-transform-private-methods to your configuration.

So I added it into my devs and modify my babel.config.js

My package.json

{
...
"jest": {
    "preset": "jest-expo",
    "globals": {
      "ts-jest": {
        "tsconfig": "tsconfig.spec.json",
        "babelConfig": true
      }
    },
    "transformIgnorePatterns": [],
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx"
    ]
  },
  "devDependencies": {
  ...
  "@babel/plugin-transform-private-methods": "^7.22.5",
  }
  ...
}

in babel.config.js
add this

{
   ...
   plugins: [
      ['@babel/plugin-transform-private-methods', { loose: true }],
   ]
}

Hope it helps to someone ❤️

osk-poita121 added a commit to osk-poita121/react-native-maps that referenced this issue Oct 3, 2023
babel config is needed to run jest tests after upgrading react-native.
See: react-native-community/upgrade-support#152
Also, it's part of most libraries either way.
GoldenDragon0710 added a commit to GoldenDragon0710/google-map-react-native that referenced this issue Nov 27, 2023
babel config is needed to run jest tests after upgrading react-native.
See: react-native-community/upgrade-support#152
Also, it's part of most libraries either way.
@xiongemi
Copy link

xiongemi commented Dec 21, 2023

i got this error when i use .babelrc or .babelrc.js in my project. it works when i change it to babel.config.json or babel.config.js.

or i change to specify the babel config file path in the jest.config.ts:

module.exports = {
  displayName: 'my-app3632808',
  preset: 'react-native',
  resolver: '@nx/jest/plugins/resolver',
  moduleFileExtensions: ['ts', 'js', 'html', 'tsx', 'jsx'],
  setupFilesAfterEnv: ['<rootDir>/test-setup.ts'],
  moduleNameMapper: {
    '\\.svg$': '@nx/react-native/plugins/jest/svg-mock',
  },
  transform: {
    '^.+\\.(js|ts|tsx)$': [
      'babel-jest',
      {
        configFile: __dirname + '/.babelrc.js', // <----- points to my babel file
      },
    ],
    '^.+\\.(bmp|gif|jpg|jpeg|mp4|png|psd|svg|webp)$': require.resolve(
      'react-native/jest/assetFileTransformer.js'
    ),
  },
  coverageDirectory: '../../coverage/apps/my-app3632808',
};

@nickkhall
Copy link

Including the above solutions, what DID work, was adding the projects to my jest.config.js in my projects root directory. I am running a mono repo, so my frontend was a directory inside the root repo. I ran npx jest in my frontend directory as well.

(note: change project-name to your projects name)
Also, having the transformIgnorePatterns and the others helps

module.exports = {
  ...,  
  projects: [                                                                     
    {                                                                             
      displayName: 'project-name',                                                
      testMatch: ['<rootDir>/src/components/**/__tests__/*.test.tsx'],            
    },
  ],
  globals: {                                                                                                                                                             
    'ts-jest': {                                                     
      tsconfig: 'tsconfig.spec.json', // as specified by ts-jest 
      babelConfig: true,                                         
    },                                                           
  },                    
  transformIgnorePatterns: [
    '/node_modules/(?!(@react-native|react-native)/).*/',
  ],                                                     
  setupFilesAfterEnv: ['@testing-library/jest-native/extend-expect'],
  testPathIgnorePatterns: [                                          
    '/node_modules/(?!(@react-native|react-native)/).*/',            
  ],                                                     
  modulePathIgnorePatterns: [                            
    '/node_modules/(?!(@react-native|react-native)/).*/',
  ]
}

My issue also had a separate issue, which was looking at the root directory, and I had to tell it to only worry about this project.

So I had to solve the original issue above, AND tell it not to look in the root project directory.

@abpbackup
Copy link

abpbackup commented Feb 1, 2024

After testing almost every solution posted above, the only combination that worked for me was the following:

Please note that I'm using EXPO 50 which recommends removing the Babel config file and use the Metro config file. I'm not sure if there is a way to solve this WITHOUT adding the Babel file.

babel.config.js ({ loose: true } is key for this to work, thanks @elenitaex5 🙏🏼)

// eslint-disable-next-line no-undef
module.exports = {
  presets: [
    'babel-preset-expo',
    '@babel/preset-typescript',
  ],
  plugins: [['@babel/plugin-transform-private-methods', { loose: true }]],
};

jest.config.js (remove the "jest" entry from your package.json

import { Config } from '@jest/types';

const config: Config.InitialOptions = {
  preset: 'jest-expo',
  globals: {
    'ts-jest': {
      tsconfig: 'tsconfig.spec.json',
      babelConfig: true,
    },
  },
  transformIgnorePatterns: [],
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
};

export default config;

Make sure you install this dev dependencies:
@babel/plugin-transform-private-methods
@babel/preset-typescript
metro-react-native-babel-preset

PainStaker0331 added a commit to PainStaker0331/react-native-maps that referenced this issue Mar 3, 2024
babel config is needed to run jest tests after upgrading react-native.
See: react-native-community/upgrade-support#152
Also, it's part of most libraries either way.
@eedeebee
Copy link

eedeebee commented Mar 5, 2024

Wow it's 2024 and it's amazing this issue is still open years later with so many solutions and none that actually work for me. I'm in a bare react native project, no expo "for reasons". And I just wanna write some test code. Amazing that it's a multi-hour research project just to write some unit tests. It actually saeems quicker to write a new test runner than to spend time learning how to configure jest and babel and all this mess. Sigh...

@iuliuvisovan
Copy link

For anyone still coming here for this issue, it could be from jest upgrade breaking the location of your babel.config.js. Basically jest 28 had a breaking change with regards to the location of the babel config.

See: https://stackoverflow.com/questions/74785831/test-suite-failed-to-run-node-modules-react-native-polyfills-error-guard-js-m

Super-CodeKing added a commit to Super-CodeKing/react_native_map that referenced this issue Apr 26, 2024
babel config is needed to run jest tests after upgrading react-native.
See: react-native-community/upgrade-support#152
Also, it's part of most libraries either way.
fairskyDev0201 pushed a commit to fairskyDev0201/react-native-maps that referenced this issue Apr 29, 2024
babel config is needed to run jest tests after upgrading react-native.
See: react-native-community/upgrade-support#152
Also, it's part of most libraries either way.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests