我在this线程中遵循了所选的答案,但我无法理解。我想测试一个TextInput组件的值,这样我就可以检查它的长度了,现在实现这个目标的正确方法是什么?
我的组件看起来像这样:
import React, {useState, useEffect} from 'react';
import {TextInput} from 'react-native';
export default function TextInputComponent(props) {
const [text, setText] = useState('');
useEffect(() => {
props.text ? setText(props.text) : setText('');
}, []);
const handleInputTextChange = text => {
setText(text);
};
return (
<TextInput
onChangeText={text => handleInputTextChange(text)}
value={text}
maxLength={maxLength}
testID="text-input"
/>
);
}到目前为止,我构建的测试文件:
import React from 'react';
import renderer from 'react-test-renderer';
import {render} from 'react-native-testing-library';
import TextInputComponent from 'components/textInputComponent/textInputComponent';
describe('<TextInputComponent />', () => {
it('renders correctly', () => {
renderer.create(<TextInputComponent />);
});
it('should show "AAA" with text="AAAA" and maxLength="3" props', () => {
const props = {
text: 'AAAA',
maxLength: 3,
};
const {queryByTestId} = render(<TextInputComponent {...props} />);
const textInput = queryByTestId('text-input');
console.log(textInput);
});
});发布于 2020-07-13 15:33:26
我认为您想要做的是将最初在道具中传递的文本限制为所传递字符的maxLength。
在组件useEffect()中,
而不是:
props.text ? setText(props.text) : setText('');切片初始文本:
props.text ? setText(props.text.slice(0, maxLength)) : setText('');这也适用于文本长度小于maxLength的情况。
https://stackoverflow.com/questions/62877505
复制相似问题