How can one use React Testing Library to target a blank <input> element that only has a type attribute?
For example I have my input that will be dynamically filled with attributes etc, similar to the label around it:
<label htmlFor={labelInput}>
{labelText}
</label>
<input
type="text"
id={labelInput}
name={labelInput}
...
/>
but while I am not passing anything to it, it will look like:
<input type="text" />
I have been reading that I can use getByRole('input') or getByRole('textbox') to target this as it has the type="text" attribute, but I can't seem to get this to work properly when asserting that other attributes aren't present.
For example, I can't get it to see that I am performing user actions to type text into the input...
const input = getByRole('textbox');
userEvent.type(input, 'some-text');
expect(input).toHaveAttribute('value', 'some-text');
This test returns:
expect(element).toHaveAttribute("value", "some-text") // element.getAttribute("value") === "some-text"
Expected the element to have attribute:
value="some-text"
Received:
null
24 |
> 25 | expect(input).toHaveAttribute('value', 'some-text');
It appears after a bit more digging that we shouldn't be using .toHaveAttribute('value'... but instead can directly query the value property of the input variable defined and found.
Performing the following test PASSES
expect(input.value).toBe('some-text');
As @MaxLarionov so kindly pointed out:
Be aware that in expect(input.value).toBe('some-text'); you are assessing that the input DOM node has a value property set to some-text. It does not assess the attribute setting. For an attribute you could use native JS:
expect(input.getAttribute('value')).toBe('some-text');