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 ..?
  });
ggorlen
  • 44,755
  • 7
  • 76
  • 106
Petro Ivanenko
  • 637
  • 2
  • 8
  • 19
  • Can you explain the question in some detail? – Darshan Jain Jan 11 '21 at 12:21
  • Related: [React Native: How to test if element is focused?](https://stackoverflow.com/questions/65890013/react-native-how-to-test-if-element-is-focused) – ggorlen Nov 07 '21 at 04:49
  • Does this answer your question? [React Native: How to test if element is focused?](https://stackoverflow.com/questions/65890013/react-native-how-to-test-if-element-is-focused) – Kia Kaha Aug 31 '22 at 14:14

1 Answers1

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.