单元测试使用带有Jest的Native Modules的React Native应用程序

时间:2017-02-02 06:14:49

标签: javascript unit-testing react-native jest

我试图用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。

由于

1 个答案:

答案 0 :(得分:0)

现在在Jest docs中描述了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)/"
]

反应原生项目中的github上也存在一个问题,讨论了这个问题:https://github.com/facebook/jest/issues/2382

希望这有帮助