Reputation: 2481
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?
Upvotes: 4
Views: 21944
Reputation: 31
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();
Upvotes: 2
Reputation: 1811
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
Upvotes: 9
Reputation: 1062
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()
Upvotes: 1
Reputation: 14816
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');
Upvotes: 0