React Native Jest测试套件失败:TypeError:无法读取未定义的属性“ propTypes”

时间:2019-09-06 01:28:01

标签: react-native jestjs

我正在尝试使用由react-native init创建的应用程序附带的Jest测试套件,但是在运行npm test时出现此错误:

TypeError: Cannot read property 'propTypes' of undefined

  at propTypes (node_modules/react-native/Libraries/Animated/src/createAnimatedComponent.js:178:31)
  at Object.oldCreate [as createAnimatedComponent] (node_modules/react-native/jest/setup.js:79:23)
  at Object.Animated (node_modules/react-navigation-stack/lib/commonjs/views/BorderlessButton.tsx:5:28)
  at Object.<anonymous> (node_modules/react-navigation-stack/lib/commonjs/views/TouchableItem.tsx:19:1)

这是测试失败的代码...

import 'react-native';
import React from 'react';
import App from '../App';

import renderer from 'react-test-renderer';

beforeAll(() => { 
  jest.mock('@react-native-community/async-storage');
});

it('renders correctly', () => {
  renderer.create(<App />);
});

不确定如何解决它,我通过模拟模块(如AsyncStorage,geolocation,NetInfo)或将其包名称添加到package.json中的jest对象中来设法解决了几个错误,如下所示:

 "jest": {
    "preset": "react-native",
    "transformIgnorePatterns": [
      "node_modules/(?!(react-native|react-native-barcode-builder|react-native-maps|react-native-android-open-settings|react-native-qrcode-scanner|react-native-permissions|react-native-camera|react-native-google-maps-directions|jsbarcode|react-native-picker-select|react-native-datepicker|react-native-touch-id|react-native-screens|react-native-gesture-handler|react-navigation|react-navigation-stack)/)"
    ]
  }

我的babel.config文件只有...

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

我缺少一些配置步骤吗?不确定是否有帮助,但是我正在使用React Native v0.60.5。预先感谢。

2 个答案:

答案 0 :(得分:0)

您应该在package.json中定义这样的jest配置。

 "jest": {
    "preset": "react-native",
    "collectCoverage": true,
    "testEnvironment": "jsdom",
    "moduleDirectories": [
      "node_modules",
      "components"
    ],
    "transform": {
      "^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
    },
    "setupFiles": [
      "<rootDir>/jest/setup.js"
    ],
    "transformIgnorePatterns": [
      "node_modules/(?!(jest-)?react-native)"
    ],
    "coveragePathIgnorePatterns": [
      "/node_modules/",
      "/jest",
      "assets",
      "lib"
    ],
    "modulePathIgnorePatterns": [
      "package",
      "assets",
      "lib"
    ]
  },

答案 1 :(得分:0)

react-native-gesture-handler添加正确的模拟为我修复了该问题。我必须添加:

"setupFiles": [
      "./node_modules/react-native-gesture-handler/jestSetup.js"
    ],

您可以在此处找到更多文档: https://kmagiera.github.io/react-native-gesture-handler/docs/getting-started.html#testing