testing-library / jest-dom

:owl: Custom jest matchers to test the state of the DOM

Home Page:https://testing-library.com/docs/ecosystem-jest-dom

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

toHaveDisplayValue does not use consider label attribute on option elements

rjgotten opened this issue · comments

  • @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] 
 }