我已经开始学习Jest来测试react native代码。在学习过程中,我遇到了fireEvent.changeText(),因为这个方法会改变值。在我的场景中,我使用这个方法来执行textInput onChangeText。在TextInput onChangeText期间,我正在更新TextInput值,同时执行基本的算术运算并将结果存储在另一个状态变量中。
我可以通过使用props访问textinput值。值,但是我如何在fireEvent.changeText()之后访问组件状态变量值。
下面是代码:Home.js
import {Text, View, StyleSheet, TextInput} from 'react-native';
import React, {Component} from 'react';
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
arithmeticValue: 0,
multiplyByTwoValue: 0,
};
}
calculateArithmeticValueWithState = num => {
this.setState({
arithmeticValue: num,
multiplyByTwoValue: num * 2,
});
};
render() {
return (
<View style={styles.container}>
<View>
<Text>Welcome to React Native... Second Snapshot Testing..</Text>
</View>
<View>
<TextInput
value={this.state.arithmeticValue}
onChangeText={val => this.calculateArithmeticValueWithState(val)}
placeholder={'Enter Postive Integer'}
testID={'integer.textinput'}
style={{
borderColor: 'grey',
borderWidth: 0.8,
borderRadius: 2,
width: 300,
}}
/>
<Text testID='mulByTwo.test'>{this.state.multiplyByTwoValue}</Text>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
justifyContent: 'center',
alignItems: 'center',
},
});
Home.test.js
import React from 'react';
import Home from './home';
import renderer from 'react-test-renderer';
import {fireEvent, render} from '@testing-library/react-native';
it('Should apply the value when changing text', () => {
const {getByTestId} = render(<Home />);
fireEvent.changeText(getByTestId('integer.textinput'), 4);
console.log(getByTestId('integer.textinput').props.value) // It return 4
// Here how can i access the component state multiplyByTwo value and it should return 8 based on the logic of getByTestId('integer.textinput')
})
搜索了很多,但没有找到答案。
任何更新,因为我也在努力解决这个问题