7

我正在尝试用jest测试react-native-camera模块

所以我有以下内容package.json

{
  "name": "app",
  "version": "0.0.1",
  "private": true,
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "react": "~15.4.0-rc.4",
    "react-native": "0.40.0",
    "react-native-camera": "^0.5.1"
  },
  "devDependencies": {
    "babel-eslint": "^7.1.1",
    "babel-jest": "18.0.0",
    "babel-preset-react-native": "1.9.1",
    "jest": "18.1.0",
    "react-test-renderer": "~15.4.0-rc.4"
  },
  "jest": {
    "preset": "react-native"
  }
}

Component并在示例中给出以下内容:

import React from 'react';
import Camera from 'react-native-camera';

class CameraComponent extends React.Component {
  constructor(props: Props) {
    super(props);

    this.camera = null;

    this.state = {
      camera: {
        aspect: Camera.constants.Aspect.stretch,
        captureTarget: Camera.constants.CaptureTarget.cameraRoll,
        type: Camera.constants.Type.back,
        orientation: Camera.constants.Orientation.auto,
        flashMode: Camera.constants.FlashMode.auto,
      }
    };
  }

  render() {
    return (
        <Camera
          ref={(cam) => {
            this.camera = cam;
          }}
          style={styles.preview}
          aspect={this.state.camera.aspect}
          captureTarget={this.state.camera.captureTarget}
          type={this.state.camera.type}
          flashMode={this.state.camera.flashMode}
          defaultTouchToFocus
          mirrorImage={false}
        />
    );
  }
}

const styles = StyleSheet.create({
  preview: {
    flex: 1
  }
}

因此,下面的测试失败并显示以下消息:

TypeError:无法读取未定义的属性“方面”

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

import renderer from 'react-test-renderer';

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

2 回答 2

8

要修复文件夹中创建react-native-camera的反应组件:__mocks__

import React from 'react';

const constants = constants = {
  Aspect: {},
  BarCodeType: {},
  Type: {},
  CaptureMode: {},
  CaptureTarget: {},
  CaptureQuality: {},
  Orientation: {},
  FlashMode: {},
  TorchMode: {}
};

class Camera extends React.Component {

  static constants = constants
  render() {
    return null;
  }
}

Camera.constants = constants;

export default Camera;

并通过添加以下行来修改测试:

import mockCamera from '../__mocks__/Camera';

jest.mock('react-native-camera', () => mockCamera);
于 2017-01-24T02:24:03.157 回答
3

您必须使用库的名称和组件的名称来模拟它,如下所示:

jest.mock('react-native-camera', () => 'Camera');

更多信息在这里:https ://facebook.github.io/jest/docs/tutorial-react-native.html#tips

于 2017-01-23T17:00:43.530 回答