0

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 Answers 2

0

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().

Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately it didn't fix the problem ...
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.