首页 > 解决方案 > 如何在 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);
    });
});

标签: react-native

解决方案


我认为您要做的是将道具中传递的初始文本限制为传递的字符的最大长度。

在您的组件useEffect()中,

代替:

props.text ? setText(props.text) : setText('');

切片初始文本:

props.text ? setText(props.text.slice(0, maxLength)) : setText('');

这也适用于文本长度小于 maxLength 的情况。


推荐阅读