jest-dom icon indicating copy to clipboard operation
jest-dom copied to clipboard

toHaveDisplayValue does not use consider label attribute on option elements

Open rjgotten opened this issue 2 years ago • 0 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.

https://github.com/testing-library/jest-dom/blob/d717c66cb4a32c806e53b287418a4013d37898fb/src/to-have-display-value.js#L51-L57

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 avatar Aug 04 '23 14:08 rjgotten