Jest.js 为什么我会收到ReferenceError:React不是定义好了吗?

42fyovps  于 2022-12-08  发布在  Jest
关注(0)|答案(1)|浏览(138)

我有一个React Native应用程序。我想用Jest添加单元测试。当我运行yarn test时,我得到以下错误:

FAIL  ./App.test.tsx
● app › can render snapshot

ReferenceError: React is not defined

   5 | describe("app", () => {
   6 |   it("can render snapshot", () => {
>  7 |     const tree = renderer.create(<App />);
     |                                  ^
   8 |     expect(tree).toMatchSnapshot();
   9 |   });
  10 | });

下面是我的App.tsx

import React from "react";
import Amplify from "aws-amplify";
import awsmobile from "./src/aws-exports";
import AppContainer from "./src/navigation/index";

Amplify.configure(awsmobile);

const App = () => {
  return (
    <AppContainer />
  );
};

下面是我的App.test.tsx中的内容:

import "react-native";
import React from "react";
import renderer from "react-test-renderer";
import App from "./App";

describe("app", () => {
  it("can render snapshot", () => {
    const tree = renderer.create(<App />);
    expect(tree).toMatchSnapshot();
  });
});

下面是我的jest.config.js

// jest.config.js
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,
    },
  },
  // This is the only part which you can keep
  // from the above linked tutorial's config:
  cacheDirectory: ".jest/cache",
  moduleFileExtensions: [
    "ios.js",
    "native.js",
    "js",
    "json",
    "jsx",
    "node",
    "ios.ts",
    "native.ts",
    "ts",
    "tsx",
  ],
};

更新日期:

下面是我的babel.config.js

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
};

我按照指示here操作。

uurv41yg

uurv41yg1#

对我来说,设置下一个配置修复了这个问题:
jest.config.js

module.exports = {
  preset: 'react-native',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  moduleDirectories: ['./node_modules', 'src'],
  cacheDirectory: '.jest/cache',
  transformIgnorePatterns: [
    '<rootDir>/node_modules/(?!@react-native|react-native)',
  ],
  moduleNameMapper: {
    '^[./a-zA-Z0-9$_-]+\\.svg$': '<rootDir>/tests/SvgStub.js'
  },
  setupFiles: ['./node_modules/react-native-gesture-handler/jestSetup.js'],
  modulePathIgnorePatterns: ['<rootDir>/packages/'],
  watchPathIgnorePatterns: ['<rootDir>/node_modules'],
}

来源:https://github.com/facebook/jest/issues/11591#issuecomment-899508417

相关问题