【问题标题】:Unit test React Native app that uses Native Modules with Jest单元测试使用带有 Jest 的 Native Modules 的 React Native 应用程序
【发布时间】:2017-02-02 06:14:49
【问题描述】:

我正在尝试使用 Jest 测试我的 React Native 应用程序。我的应用使用了一些原生模块,我什至无法运行初始测试。

我的应用程序使用具有本机依赖项的组件react-native-camera

初步测试:

import 'react-native';
import React from 'react';
import Index from '../index.ios.js';

// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';

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

当我运行它时,我收到以下错误:

失败__tests__/index.android.js
● 测试套件无法运行

TypeError: Cannot read property 'Aspect' of undefined

  at Object.<anonymous> (node_modules/react-native-camera/index.js:250:78)

如何绕过本机模块导致的此类错误?浅渲染还是类似的?

我使用 RN 0.39。

谢谢

【问题讨论】:

    标签: javascript unit-testing react-native jestjs


    【解决方案1】:

    Jest 文档中现在描述了 react-native:

    https://facebook.github.io/jest/docs/tutorial-react-native.html#transformignorepatterns-customization

    transformIgnorePatterns 选项可用于将被 babel 转换的文件列入白名单或黑名单。遗憾的是,许多 react-native npm 模块在发布之前并未预编译其源代码。

    默认情况下,jest-react-native 预设只处理项目自己的源文件和 react-native。如果您有需要转换的 npm 依赖项,您可以通过将 react-native 以外的模块列入白名单来自定义此配置选项:

    "transformIgnorePatterns": [
      "node_modules/(?!react-native|my-project|react-native-button)/"
    ]
    

    react-native 项目中的 github 上也有一个 issue 讨论这个问题:https://github.com/facebook/jest/issues/2382

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2016-09-14
      • 2017-07-05
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      • 2016-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多