4

I use react-testing-library in my application. Normally, to check if the input is in the form, we use getByLabelText. For example:

getByLabelText(/name/i)

But what if my input does not have any label? This is because of the design (UI) so I cannot have a label for the input. How can I check if that input exists in the form?

4 Answers 4

9

You can use the following to target a text input field.

getByRole('textbox', {name: /name/i})

More info https://testing-library.com/docs/queries/about#priority

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

2 Comments

How can I know that I get the correct input? For example, my input's name is "name"
If you need to verify, you could always assign that to a variable and then use screen.debug(variableName);
2

You can also add an aria-label to your input:

<TextField inputProps={{'aria-label': "example" }} />

and then in your test:

expect(screen.getByRole("textbox", { name: "example"})).toBeInTheDocument();

Comments

1

You could add a test ID to the input that solely will be used for testing purposes.

<input data-testid="your-id" />

And in your test you would do a query rather than get as get will fail the test if the element doesn't exist at all.

expect(queryByTestId('your-id')).toBeInTheDocument()

Or you could search by display value to look for the input value

expect(queryByDisplayValue('input-value')).toBeInTheDocument()

Comments

0

If you don't know an expected text in your input, you can add "data-testid" to your input and find it like that:

<input data-testid="my-input"/>

const myInput = getByTestId('my-input');

2 Comments

Can I get it by the input's name? I don't think we should add data-testid to all the inputs. I have around 30 inputs in my form
As far as I remember, you can by digging through document. But it's a messy job.

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.