Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

toHaveDisplayValue does not use consider label attribute on option elements #507

Open
rjgotten opened this issue Aug 4, 2023 · 0 comments

Comments

@rjgotten
Copy link

rjgotten commented Aug 4, 2023

  • @testing-library/jest-dom version: 5.17

Relevant code or config:

<select data-testid="dropdown">
  <option value="apple" label="Apple"></option>
  <option value="banana" label="Banana"></option>
</select>
const dropdown = screen.getByTestId("dropdown");
expect(dropdown).toHaveDisplayValue("Apple");
Expected: ["Apple"]
Received: [""]

Problem description:

toHaveDisplayValue produces the wrong result when using the standards compliant label attribute on HTMLOptionElement to supply the option text contents. Using inner text content on the element is actually the fallback for when the label attribute is not provided, but the toHaveDisplayValue matcher currently only considers .textContent.

function getValues(tagName, htmlElement) {
return tagName === 'select'
? Array.from(htmlElement)
.filter(option => option.selected)
.map(option => option.textContent)
: [htmlElement.value]
}

Suggested solution:

Consider also the label attribute. E.g.

function getValues(tagName, htmlElement) { 
   return tagName === 'select' 
     ? Array.from(htmlElement) 
         .filter(option => option.selected) 
         .map(option => option.hasAttribute('label') ?  option.getAttribute('label') : option.textContent) 
     : [htmlElement.value] 
 }
@rjgotten rjgotten changed the title toHaveDisplayValue does not correctly report displayed value for select options toHaveDisplayValue does not report displayed value for option elements using label attribute Aug 4, 2023
@rjgotten rjgotten changed the title toHaveDisplayValue does not report displayed value for option elements using label attribute toHaveDisplayValue does not use consider label attribute on option elements Aug 4, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant