如果在新的React版本0.57和TypeScript中将test与Jest和Ezyme集成在一起,它们将无法工作.以下是复制的步骤:

创建一个新的本地项目:

react-native init MyApp -package "com.my.app" --template typescript && node MyApp/setup.js

安装所有Jest和Enzyne相关软件包:

npm install --save-dev react-dom enzyme enzyme-react-adapter-16 jest-fetch-mock ts-jest

添加jest配置:

"jest": {
  "preset": "react-native",
  "moduleFileExtensions": [
    "ts",
    "tsx",
    "js"
  ],
  "transform": {
    "^.+\\.(js)$": "<rootDir>/node_modules/babel-jest",
    "\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
  },
  "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
  "testPathIgnorePatterns": [
    "\\.snap$",
    "<rootDir>/node_modules/"
  ],
  "cacheDirectory": ".jest/cache",
  "setupFiles": [
    "./tests/setup.js"
  ]
}

添加文件tests/setup.js并包括以下配置:

import Enzyme from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import { NativeModules } from "react-native";

global.fetch = require("jest-fetch-mock"); // eslint-disable-line no-undef
jest.mock("react-native-config");
Enzyme.configure({ adapter: new Adapter() });

最后但并非最不重要的一点是,添加一个基本测试(App.test.tsx)来判断Jest和Enzyme 是否有效:

import React from "react";
import { shallow } from "enzyme";
import { View } from "react-native";
import App from "./App";

const createTestProps = props => ({
  ...props
});

describe("App", () => {
  describe("rendering", () => {
    let wrapper;
    let props;
    beforeEach(() => {
      props = createTestProps({});
      wrapper = shallow(<App {...props} />);
    });

    it("should render a <View />", () => {
      expect(wrapper.find(View)).toHaveLength(1);
    });
  });
});

如果现在try 运行测试,则会收到以下错误消息:

 FAIL  app/App.test.tsx
  ● Test suite failed to run

    Couldn't find preset "module:metro-react-native-babel-preset" relative to directory "<Directory"

编辑

这似乎和巴贝尔有关.

推荐答案

我在这个问题上找到了答案:https://github.com/facebook/metro/issues/242#issuecomment-421139247

基本上,将此添加到package.json中的Jest 部分:

"transform": { "^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js" }

React-native相关问答推荐

@testing-library/react-native -> 渲染 -> TypeError:无法读取未定义的属性(读取存在)

如何在底部标签导航中添加顶部标签

reactnavigation后退按钮的自定义后退导航

在 React Native Paper 中更改 TextInput 的文本 colored颜色

带有 SafeAreaView-wrapper 的 react-native Modal 不起作用

React Native 中如何使用 Flex 居中组件?

用于 React-Native 开发的 Visual Studio Code 中的自动导入

React-Native Packager 失败:重复的模块名称

Xcode 12 问题:Build input file cannot be found

React-Native iOS - 如何通过按下按钮从 React-Native 视图导航到非 React-Native 视图(本机 iOS 视图控制器)?

带有 react-navigation 的 DrawerNavigation 标头

React-native Xcode 构建失败 -> 'RCTAssert.h file not found'

React Native 检测点击 View

axios 的网络错误和react-native

TypeError : props.navigation.getParam 不是函数. In(props.navigation.getParam('name')

如何在react-native中关闭模态

如何在 React Native 中将图像放置在其他图像之上?

Expo在使用Windows 10的android模拟器上运行

ReactNative Flatlist - RenderItem not working

无法读取未定义的属性 string| React.PropTypes | LayoutPropTypes.js