Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-native, jest, ts-jest: ReferenceError: React is not defined

I have been struggling for a couple of days now to get tests running for simple react-native with expo + typescript + jest + ts-jest. I have already asked a related question here Here is the setup of my project:

  1. tsconfig.json
    {
      "compilerOptions": {
        "noEmit": true,
        "lib": ["dom", "esnext"],
        "jsx": "react-native",
        "moduleResolution": "node",
        "allowSyntheticDefaultImports": true,
        "skipLibCheck": true
      }
    }
  1. babel.config.json
module.exports = function(api) {
  api.cache(true);
  return {
    presets: ["babel-preset-expo"]
  };
};
  1. jest.config.js (see official github setting of react-native + ts-jest)
const { defaults: tsjPreset } = require("ts-jest/presets");
module.exports = {
  ...tsjPreset,
  preset: "react-native",
  transform: {
    ...tsjPreset.transform,
    "\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
  },
  globals: {
    "ts-jest": {
      babelConfig: true
    }
  },
  cacheDirectory: ".jest/cache"
};

I get this error

ReferenceError: React is not defined

because I am importing react like this in my file: import React from 'react'

If I import like import * as React from 'react' it works.

Any help will be greatly appreciated as I have spent already a few days in this project.

like image 994
TheSoul Avatar asked Mar 03 '23 16:03

TheSoul


1 Answers

I had the exact same issue and fixed it by changing my tsconfig.json from

{
  "compilerOptions": {
    /* Basic Options */
    "target": "esnext" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
    "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
    "lib": [
      "es6"
    ] /* Specify library files to be included in the compilation. */,
  ...
  }
}

to

{
  "compilerOptions": {
    /* Basic Options */
    "target": "es2017" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
    "module": "ESNext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
    "lib": [
      "es2017"
    ] /* Specify library files to be included in the compilation. */,
  ...
  }
}
like image 106
Simon Reggiani Avatar answered Mar 10 '23 12:03

Simon Reggiani