getAllByRole does not find input element in react native testing library

141 Views Asked by At

I have a simple component with two inputs and one button. I was able to test the code with getAllByRole func for buttons. But when I want to find input elements, I got below error :

Unable to find an element with role: "textbox"

This is my code :

import React from "react";
import { View, TextInput, Button } from "react-native";


const ListComp = () => {
    return (
        <View>
            <TextInput />
            <TextInput />
            <Button title="Test"/>
        </View>
    )
}

export default ListComp;

and this is test file :

import React from 'react';
import ListComp from './ListComp';
import {
    render,
    screen,
} from '@testing-library/react-native';

test('renders correctly', () => {
    render(<ListComp />);
    expect(screen.getAllByRole('textbox')).toHaveLength(2);
});
2

There are 2 best solutions below

1
Mister_CK On

GetByRole uses the prop "accessibilityRole". Your TextInputs don't seem to have one so it won't work. Button has one by default, but this is not true for every element. Adding an accessibilityRole should fix your issues. There however doesn't seem to be a role for "textBox" according to the docs: https://reactnative.dev/docs/accessibility. You could add an accesibilityLabel and use getAllByLabelText:

const ListComp = () => {
    return (
        <View>
            <TextInput accessibilityLabel ="textbox" />
            <TextInput accessibilityLabel ="textbox" />
            <Button title="Test"/>
        </View>
    )
}

Although you might want to consider adding a placeHolderText and getting by that instead: screen.getByPlaceholderText().

0
Uzaq Sahillərdə On

Example Component:

      <Text>Name:</Text>
      <TextInput
        value={name}
        onChangeText={setName}
        style={{width: '100%', height: 50, backgroundColor: 'pink'}}
        testID="textbox"
      />
      <Text>Email:</Text>
      <TextInput
        value={email}
        onChangeText={setEmail}
        style={{width: '100%', height: 50, backgroundColor: 'pink'}}
        testID="textbox"
      />

Testing the count of TextInputs:

  const textInputs = getAllByTestId('textbox');

  expect(textInputs.length).toBe(2);