testing-library/react-testing-library

Not able to set readonly attribute from React component boolean prop.

Closed this issue · 1 comments

  • @testing-library/react 16.2.0:
  • Testing Framework and version: jest 29.7.0
  • DOM Environment: jest-environment-jsdom 29.7.0

Relevant code or config:

it('renders as read-only when isEditable is false', async () => {
    render(<DataField {...defaultProps} isEditable={false} />);

    await waitFor(() => {
      const inputField = screen.getByRole('textbox');
      expect(inputField).toHaveAttribute('readonly', 'true');
    })
  });

What you did:

Called an above test case under a test file

What happened:

<input
checked={isChecked}
type={type}
readOnly={!isEditable}
defaultValue={defaultValue}
className={p-2 rounded-md w-[${props.width || "100%"}] border-[1px] border-grey bg-white self-start focus:outline-none focus:border-[1.5px] focus:border-primary}
{...props}
/>
I am calling component which has the above input. I am setting readOnly attribute to the !isEditable prop.

Reproduction:

  • Render a react component passing a boolean prop
  • Add a html input under a component and assign readOnly attribute to the boolean prop.
  • Noticed readonly is assigned to an empty string ""

Problem description:

The expected behaviour is readonly attribute should be set to true. but It's been assigned to ""

  Expected the element to have attribute:
      readonly="true"
    Received:
      readonly=""

Suggested solution:

This isn't related to testing-library but a DOM behavior for Boolean values. Presence actually means true and AFAIR this is also how JSDOM behaves. More information in MDN regarding boolean attributes: https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML