React Native 测试元素的焦点

fgw7neuy  于 2023-02-05  发布在  React
关注(0)|答案(1)|浏览(113)

我如何检查这个TextInput组件是否有焦点?我知道如何做on the web

const input = getByPlaceholderText("placeholder");
expect(document.activeElement).toEqual(input);

但是如何在React Native中做到这一点呢?

it('should have focus', () => {
    const { getByTestId } = render(<TextInput autoFocus testID={ 'alpha' }/>);
    const textInput = getByTestId('alpha');

    // and then ..?
  });
0lvr5msh

0lvr5msh1#

Idk如果它仍然帮助你,但对于其他寻找答案的人,我这样做:
上下文:我正在创建一个可定制的字段,所以我需要当我点击组件的任何部分(包括标签)时,都有焦点。
文件输入.ts

import {
      TextInput,
      TextInputProps,
      Text
    } from 'react-native';
  
export type InputProps = { label: string } & TextInputProps;

export default function Input(props: InputProps){
  const [hasFocus, setHasFocus] = useState(false)
  const inputRef = useRef<TextInput>(null);

  const handleFocus = () => {
    inputRef.current?.focus();
    setHasFocus(true);
  }

  return (
  <TouchableWithoutFeedback
    onPress={handleFocus}
    accessibilityLabel={`${props.label} field`}>
    <Text>{props.label}</Text>
    <TextInput
      accessibilityState={{ selected: hasFocus }}
      testID={`${props.label}-input`}
      onBlur={(event) => {
                  setHasFocus(false);
                  props?.onBlur()
                }}
    />
  </TouchableWithoutFeedback>)
}

文件输入.test.ts

test('should focus text input', async () => {
    const container = render(
      <Input label="Render Label"/>
    );

    fireEvent.press(container.getByLabelText('Render Label field'));

    expect(container.getByTestId('Render Label-input')).toHaveAccessibilityState({ selected: true });
  });

注意::如果您能够通过testID或accessibilityLabel引用输入,并在测试中触发changeText事件,将其与新值进行比较。祝贺组件获得焦点。

相关问题