5

I'm using Material-UI and React Testing Library in a project and I'm having a hard time with TextField that is set to type="password". I understand that, in tests, it's not a good practice to default to getting an element using testId field, but I cannot find a way to get to the password input field. I cannot use getByRole because apparently <input type="password"> doesn't have a role. There is no text in the input box, nor placeholder text, and when I try to use getByLabelText I'm getting this error message:

TestingLibraryElementError: Found a label with the text of: Password, however no form control was found associated to that label. Make sure you're using the "for" attribute or "aria-labelledby" attribute correctly. 

When I reviewed the rendered elements in the test (I used screen.debug()), I realize that this is how Material-UI composes the TextField:

<div> <div class="MuiFormControl-root MuiTextField-root MuiFormControl-fullWidth" > <label class="MuiFormLabel-root MuiInputLabel-root MuiInputLabel-formControl MuiInputLabel-animated" data-shrink="false" > Password </label> <div class="MuiInputBase-root MuiInput-root MuiInput-underline MuiInputBase-fullWidth MuiInput-fullWidth MuiInputBase-formControl MuiInput-formControl" > <input aria-invalid="false" class="MuiInputBase-input MuiInput-input" name="pass" type="password" value="" /> </div> </div> </div>

So, the <input> is not embedded inside the <label> and also the label doesn't have a for attribute to associate it with the input. So, how else would I be able to get a hold of that password box without using testId?

1 Answer 1

10

I think you need to set the id prop to TextField for it to associate the label to the input

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

2 Comments

How would this look? I tried passing this to SelectProps and MenuProps without luck
@Michael <TextField id="string-you-want-to-be-the-id-of-the-child-input" ... />, then that string will be used for both the id of the input and the for of the label.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.