vitest icon indicating copy to clipboard operation
vitest copied to clipboard

`toHaveValue()` does not support `listbox` role for non-select elements

Open 0xTadash1 opened this issue 1 year ago • 1 comments

Clear and concise description of the problem

Currently, in browser mode, toHaveValue() does not work well with listbox role elements other than <select>

Image

The following two code snippets are semantically similar.

<ul role="listbox" aria-multiselectable="true">
  <li role="option" value="first">First Value</li>
  <li role="option" value="second" aria-selected="true">Second Value</li>
  <li role="option" value="third" aria-selected="true">Third Value</li>
</ul>
<select multiple>
  <option value="first">First Value</option>
  <option value="second" selected>Second Value</option>
  <option value="third" selected>Third Value</option>
</select>

Suggested solution

Supporting both would be helpful, as some UI component libraries generate the first one.

Alternative

No response

Additional context

Here is the reproducible CodeSandbox:

https://codesandbox.io/p/devbox/laughing-joliot-ssvs7n?file=%2Fsrc%2FListbox.test.tsx

After preparing this CodeSandbox, I noticed the stackblitz in the docs... If this is insufficient, please let me know and I will recreate it in stackblitz.

Validations

0xTadash1 avatar May 02 '25 11:05 0xTadash1

I'd like to pick this up. Here's what I have in mind:

For an element with role="listbox" that isn't a <select>, toHaveValue() would read the role="option" elements inside it that have aria-selected="true":

  • with aria-multiselectable="true", the value is an array, like <select multiple>
  • otherwise it's the single selected value, or undefined if nothing is selected
  • an option's value is its value attribute, falling back to its text content, the same way <option> works

So the example from the issue would pass with toHaveValue(['second', 'third']).

toHaveFormValues only reads real form controls, so it stays as it is, and I'd keep toHaveDisplayValue out of scope too.

Does this sound right? If so, could this get the approved label so I can open a PR?

nomadical avatar Nov 02 '26 10:11 nomadical