Test focus of element
Asked Answered
U

1

3

How do I check that this TextInput component is focused? I know how to do it on the web:

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

But how to do the same in React Native?

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

    // and then ..?
  });
Ulna answered 11/1, 2021 at 12:11 Comment(3)
Can you explain the question in some detail?Marvelous
Related: React Native: How to test if element is focused?Bostow
Does this answer your question? React Native: How to test if element is focused?Xenogamy
M
0

Idk if it still helps you, but for the other people looking for answers, I did it like this:

Context: I was creating a customizable field, so I needed that when I tapped on any part of the component (including the label) there would be focus. I also used the accessibility props to help me with this

file Input.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>)
}

file Input.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 });
  });

Notes:: if you were able to reference the input, either by testID or accessibilityLabel and triggered a changeText event in the test comparing it with the new value. Congratulations the component was focused.

Maundy answered 4/2, 2023 at 20:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.