Stack Exchange
Polyfills Jest Test Fail type ErrorHandler = (error: mixed, isFatal: boolean) => void;
I am trying to use Jest and only test the rendering, here's my test file:
import "react-native"; 
import React from "react"; 
import App from"../src/Root/"; 
import { create } from "react-test-renderer";

describe("App", () => {
 const tree = create(<App />).toJSON();  
 it("renders correctly", () => {
  expect(tree).toMatchSnapshot();
 }); 
});

when I run yarn test, I got an error
Error message:
  /dic/node_modules/react-native/Libraries/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:1350:14)
      at Object.<anonymous> (node_modules/react-native/jest/setup.js:16:6)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.128 s

babel.config.js
module.exports = {
  presets: [
    ["@babel/preset-env", { targets: { node: "current" } }],
    "@babel/preset-typescript",
  ],
  plugins: [["module:react-native-dotenv"], "react-native-reanimated/plugin"],
};

jest.config.js
module.exports = {
  preset: "react-native",

  moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
  transform: {
    "^.+\\.(js|jsx)$": "babel-jest",
    "^.+\\.(ts|tsx)$": "ts-jest",
  },
  transformIgnorePatterns: [
    "node_modules/(?!(jest-)?@react-native|react-(native|universal|navigation)-(.*)|@react-native-community/(.*)|@react-navigation/(.*)|bs-platform|(@[a-zA-Z]+/)?(bs|reason|rescript)-(.*)+)",
  ],
};

I've followed tons of solutions attempt online but I can't find that fit to my problem, including adding react-native to transformIgnorePatterns

What is the purpose of import "react-native"? It's unclear why the error happens because there's no rule for react-native in transformIgnorePatterns. Any way, you shouldn't import react-native directly or indirectly as it contains platform-specific code. Mock it where needed

It's been there since I init the project. I just try to run the test after 6 months of development. transformIgnorePatterns is there because there's another issue that needs it. I also go through every package's docs to create the mock file. I never touch the test file.

It likely shouldn't be there. In case it should, you need to mock react-native.

Might want to create a pull request to tell them that they should remove the import

any workaround?

try this solution https://stackoverflow.com/a/70688992/3687017
