我正在尝试使用react-native-camera
测试jest模块所以我有以下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"
}
}
并考虑example中的以下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:无法读取未定义的属性'Aspect'
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 />
);
});
答案 0 :(得分:7)
修复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);
答案 1 :(得分:2)
你必须使用库的名称和组件的名称来模拟它,如下所示:
jest.mock('react-native-camera', () => 'Camera');
此处有更多信息:https://facebook.github.io/jest/docs/tutorial-react-native.html#tips