Tengo una clase para mi botón personalizado:
import React, { Component } from 'react';
import { StyleSheet, View, TouchableHighlight, Text, Image } from 'react-native';
class NavBarBackButton extends Component {
static propTypes = {
onClick: React.PropTypes.func.isRequired,
buttonText: React.PropTypes.string,
customStyle: React.PropTypes.object
};
render() {
return (
<TouchableHighlight
style={[styles.backButton, this.props.customStyle]}
onPress={() => {this.props.onClick()}} >
<View style={{flexDirection: 'row'}}>
<Image
style={styles.backImage}
source={require('../img/back-128.png')}
/>
<Text style={styles.backButtonText}>
{this.props.buttonText}
</Text>
</View>
</TouchableHighlight>
);
}
}
const styles = StyleSheet.create({
backButton: {
justifyContent: 'center'
},
backButtonText: {
fontSize: 17,
textAlignVertical: 'center',
color: 'black',
},
backImage: {
width: 40,
height: 40
},
});
export default NavBarBackButton;
y la instantánea se genera con esta prueba:
import 'react-native';
import React from 'react';
import NavBarBackButton from '../navBarBackButton';
import renderer from 'react-test-renderer';
function doWork() {
console.log('Back button was clicked!');
}
it('renders all UI elements', () => {
const tree = renderer.create(
<NavBarBackButton onClick = {doWork}/>
).toJSON();
expect(tree).toMatchSnapshot();
});
pero cuando agrego otro accesorio al elemento <TouchableHighlight/>
, como:
underlayColor={'blue'}
y vuelva a ejecutar la prueba: no obtengo una diferencia que muestre que la instantánea no esperaba este accesorio adicional. De hecho, el único accesorio que evaluó las costuras era "estilo".
¿Está este trabajo en progreso?
Además, en una nota relacionada, ¿por qué el tipo de TouchableHighlight se muestra en la instantánea (y el depurador) como 'Ver' y no como 'TouchableHightlight'?
En mi package.jason tengo:
{
"name": <my_project_name>,
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"jest": {
"preset": "jest-react-native",
"collectCoverage": true,
"verbose": true,
"preprocessorIgnorePatterns": [
"node_modules/(?!react-native|<my_project_name>|react-native-button)"
]
},
"dependencies": {
"lodash": "^4.15.0",
"react": "^15.3.1",
"react-native": "^0.33.0",
},
"devDependencies": {
"babel-jest": "^15.0.0",
"babel-polyfill": "^6.13.0",
"babel-preset-react-native": "^1.9.0",
"jest": "^15.1.1",
"jest-cli": "^15.1.1",
"jest-react-native": "^15.0.0",
"react-addons-test-utils": "^15.2.1",
"react-shallow-testutils": "^2.0.0",
"react-test-renderer": "^15.3.1"
}
}
y mi .babelrc en directorio raíz es:
{
"presets": ["react-native"]
}
No nos burlamos específicamente de TouchableHighlight. Se representa como Vista porque eso es a lo que reacciona-native lo representa.
Parece que TouchableHighlight establece accesorios directamente en su elemento de respaldo nativo: https://github.com/facebook/react-native/blob/master/Libraries/Components/Touchable/TouchableHighlight.js#L200 y necesitaría una simulación especial para que lo haga para que su prop aparezca en la salida renderizada.
Una cosa que podría funcionar podría ser crear su propio simulacro como se sugiere en el segundo ejemplo en el sitio web: http://facebook.github.io/jest/docs/tutorial-react-native.html#mock -native-modules- usando-broma-simulacro
jest.mock('TouchableHighlight', () => {
const jestReactNative = require('jest-react-native');
return jestReactNative.mockComponent('TouchableHighlight');
});
@cpojer ¡ Gracias por la rápida respuesta! Mi instantánea se ve mucho más limpia ahora.
Pregunta adicional: actualmente mi salida se queja de que no estoy cubriendo una línea que especifica onPress
prop como una función pasada
static propTypes = {
onClick: React.PropTypes.func.isRequired,
...
};
<TouchableHighlight
onPress={() => {this.props.onClick()}} > //no coverage for this line of code in test
...
</TouchableHighlight>
¿Alguna idea de cómo puedo simular el clic de un botón? ¿O hacer algo para que mi prueba cubra onPress={() => {this.props.onClick()}} >
? No pude encontrar nada en sus tutoriales sobre el tema.
¡Gracias por adelantado!
@rosiakr Sí, puede probar el evento de clic de botón.
Aquí hay un código que escribí para probar el clic del botón.
class YourComponent extends Component {
handleButtonClick = () => {};
render() {
return <Button transparent onPress={() => this.handleButtonClick()}></Button>
}
}
//jest
it("Test Component", () => {
const component = renderer.create(
<YourComponent/>
);
// manually trigger the button click.
component.getInstance().handleButtonClick();
};
Comentario más útil
@cpojer ¡ Gracias por la rápida respuesta! Mi instantánea se ve mucho más limpia ahora.
Pregunta adicional: actualmente mi salida se queja de que no estoy cubriendo una línea que especifica
onPress
prop como una función pasada¿Alguna idea de cómo puedo simular el clic de un botón? ¿O hacer algo para que mi prueba cubra
onPress={() => {this.props.onClick()}} >
? No pude encontrar nada en sus tutoriales sobre el tema.¡Gracias por adelantado!