react-native, jest, ts-jest: ReferenceError: React 未定义

The*_*oul 3 jestjs react-native expo ts-jest

我已经努力了几天,以便使用 expo + typescript + jest + ts-jest 为简单的 react-native 运行测试。我已经 这里问了一个相关的问题这是我的项目的设置:

  1. 配置文件
    {
      "compilerOptions": {
        "noEmit": true,
        "lib": ["dom", "esnext"],
        "jsx": "react-native",
        "moduleResolution": "node",
        "allowSyntheticDefaultImports": true,
        "skipLibCheck": true
      }
    }
Run Code Online (Sandbox Code Playgroud)
  1. babel.config.json
module.exports = function(api) {
  api.cache(true);
  return {
    presets: ["babel-preset-expo"]
  };
};
Run Code Online (Sandbox Code Playgroud)
  1. jest.config.js(见官方github设置 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"
};

Run Code Online (Sandbox Code Playgroud)

我收到这个错误

ReferenceError: React is not defined

因为我在我的文件中导入这样的反应: import React from 'react'

如果我像import * as React from 'react' 它一样导入。

任何帮助将不胜感激,因为我已经在这个项目中度过了几天。

Sim*_*ani 6

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. */,
  ...
  }
}
Run Code Online (Sandbox Code Playgroud)

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. */,
  ...
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这个解决方案对我有用(expo sdk39)。有什么解释吗? (2认同)

归档时间:

查看次数:

1066 次

最近记录:

6 年,6 月 前