I am trying to test react-native-camera module with jest
So I have the following 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"
}
}
And given the following Component
as it is in the example:
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
}
}
So the test below is failing with the following message:
TypeError: Cannot read property 'Aspect' of undefined
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 />
);
});
Mocking native modulesMake sure that the path to the file in setupFiles is correct. Jest will run these files before running your tests, so it's the best place to put your global mocks. If you're not using Jest, then you'll need to mock these modules according to the test framework you are using.
To fix that created react-native-camera
react component in __mocks__
folder:
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;
And modified the test by adding the following lines:
import mockCamera from '../__mocks__/Camera';
jest.mock('react-native-camera', () => mockCamera);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With