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

时间:2019-07-24 11:48:10

标签: react-native jestjs expo ts-jest

我已经苦苦挣扎了几天,才能使用expo +打字稿+ jest + ts-jest为简单的react-native运行测试。 我已经问了一个相关的问题here 这是我的项目的设置:

  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(请参见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"
};

我收到此错误

ReferenceError: React is not defined

因为我要在我的文件中输入以下反应: import React from 'react'

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

由于我已经在该项目中花费了几天的时间,任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我遇到了完全相同的问题,并通过将tsconfig.json更改为

来解决了该问题
{
  "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. */,
  ...
  }
}

{
  "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. */,
  ...
  }
}