jest-dom
jest-dom copied to clipboard
toHaveSelectionValue
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')
This could be a nice addition indeed.
One thing I'd suggest is discuss the name a bit. toHaveSelectionValue can suggest it being about what's the currently selected value in a list or something like that. How about something like toHaveSelectedText instead?
I'd be fine with just toHaveSelection.
I think selection (as opposed to selected) makes more sense because that's the term used by the DOM (element.selectionStart, element.selectionEnd, element.setSelectionRange, window.getSelection()).
I also thought about toHaveSelection, but I would expect it to work also on elements other than text fields. Since my proposal is only for text fields, value matches the DOM attribute. But if we agree that it should work for other elements as well, I would go for toHaveSelection or toHaveSelectionText. 👍
Sure. Selection makes more sense than selected. toHaveSelection is great.
Hello, I would like to try to implement this one if it is still needed.