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

toHaveSelectionValue

Open diegohaz opened this issue 5 years ago • 5 comments

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')

diegohaz avatar Aug 23 '20 12:08 diegohaz

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?

gnapse avatar Aug 24 '20 12:08 gnapse

I'd be fine with just toHaveSelection.

nickserv avatar Aug 24 '20 12:08 nickserv

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. 👍

diegohaz avatar Aug 24 '20 13:08 diegohaz

Sure. Selection makes more sense than selected. toHaveSelection is great.

gnapse avatar Aug 24 '20 13:08 gnapse

Hello, I would like to try to implement this one if it is still needed.

pwolaq avatar Oct 15 '21 07:10 pwolaq