4

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

  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 (请参阅react-native + ts-jest 的官方 github 设置
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'

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

4

1 回答 1

7

我遇到了完全相同的问题,并通过更改我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. */,
  ...
  }
}

{
  "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. */,
  ...
  }
}
于 2019-12-02T03:03:38.560 回答