Describe the feature you'd like:
I'm testing a combobox element with a behavior that is quite similar to the address bar in the browser. That is, when you start typing, it automatically completes the text with the first suggestion and highlights the completion string.
I would like to test this selection behavior.
Suggested implementation:
function toHaveSelectionValue(element, value) {
const { selectionStart, selectionEnd } = element;
const selectionValue = element.value.slice(selectionStart, selectionEnd);
return {
pass: selectionValue === value,
...
};
}
Describe alternatives you've considered:
I can check the selectionStart and selectionEnd properties on the HTMLInputElement, but this is not as easy to read. And I also have to explicitly cast the element if I'm using TypeScript.
const input = getByLabelText("Fruits") as HTMLInputElement;
// Expect "pple" to be selected in "Apple"
expect(input.selectionStart).toBe(1);
expect(input.selectionEnd).toBe(5);
So, for now, I'm using an expectSelectionValue util function in my app.
Teachability, Documentation, Adoption, Migration Strategy:
toHaveSelectionValue
toHaveSelectionValue(value: string)
This allows you to check whether the given textbox element has the specified selected (highlighted) value. It accepts <input type="text"> and <textarea> elements.
Examples
<input type="text" value="text" data-testid="input" />
Using DOM Testing Library
const input = getByTestId('input')
input.setSelectionRange(1, 3)
expect(input).toHaveSelectionValue('ex')
Describe the feature you'd like:
I'm testing a combobox element with a behavior that is quite similar to the address bar in the browser. That is, when you start typing, it automatically completes the text with the first suggestion and highlights the completion string.
I would like to test this selection behavior.
Suggested implementation:
Describe alternatives you've considered:
I can check the
selectionStartandselectionEndproperties on theHTMLInputElement, but this is not as easy to read. And I also have to explicitly cast the element if I'm using TypeScript.So, for now, I'm using an
expectSelectionValueutil function in my app.Teachability, Documentation, Adoption, Migration Strategy:
toHaveSelectionValueThis allows you to check whether the given textbox element has the specified selected (highlighted) value. It accepts
<input type="text">and<textarea>elements.Examples
Using DOM Testing Library