react-native - 如何在 react-native 中测试 TextInput 的值
问题描述
我在这个线程中遵循了选择的答案,但我无法弄清楚。我想测试一个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);
});
});
解决方案
我认为您要做的是将道具中传递的初始文本限制为传递的字符的最大长度。
在您的组件useEffect()
中,
代替:
props.text ? setText(props.text) : setText('');
切片初始文本:
props.text ? setText(props.text.slice(0, maxLength)) : setText('');
这也适用于文本长度小于 maxLength 的情况。
推荐阅读
- c# - IApplicationBuilder 不包含 UseIdentity 的定义
- python - 如何在 keras 中使用 1D conv 神经网络解决音频信号问题
- bash - Asuswrt/Ubuntu 18.04 通过终端获取所有网络接口的网关
- laravel - 预期响应代码 250,但得到代码“530”
- django - 尝试在将 django 模型保存到数据库之前对其进行验证。使用 POST api 在特定模型中创建模型对象
- android - Dagger 2 未注入,lateinit 属性未初始化
- c# - 转换`IObservable
` 到 `IEnumerable >`? - google-sheets - 当我将多行文本粘贴到 Google 电子表格时,为什么这些行有时会放置一个单元格?
- .htaccess - .htaccess - 使用 PHP GET 变量重写和重定向博客 URL
- tensorflow - 无法将 NumPy 数组转换为张量