CorayThan
CorayThan

Reputation: 17825

Selecting text with Cypress

I'm trying to select text within a textarea using Cypress, but running into some issues. The Cypress api doesn't have an out of the box way to do it that I can find, so I tried implementing it myself.

I found this stackoverflow answer about selecting text and decided to follow its example. What I've arrived at is this:

selectTextWithin = (selector: string) => {
    cy.document().then((doc: Document) => {
        cy.window().then((win: Window) => {
            cy.get(selector).then((textElement: JQuery<HTMLElement>) => {
                if (win.getSelection) {
                    const selection = win.getSelection();
                    const range = doc.createRange();
                    range.selectNodeContents(textElement.get(0));
                    selection.removeAllRanges();
                    selection.addRange(range);
                } else {
                    throw new Error("Can't select text.")
                }
            })
        })
    })
}

It executes without error, but it doesn't appear to be selecting any text.

Upvotes: 1

Views: 3858

Answers (1)

Joshua Wade
Joshua Wade

Reputation: 5293

The answer you linked to deals with selecting text specifically outside an input field. Here is an answer for selecting text in an input field.


They posted a demo, and I've modified it for Cypress.

HTML:

<html>
  <body>
    <textarea type="textarea" name="message" id="message">Hello World</textarea>
  </body>
</html>

Cypress:

function createSelection(field, start, end) {
    if( field.createTextRange ) {
        var selRange = field.createTextRange();
        selRange.collapse(true);
        selRange.moveStart('character', start);
        selRange.moveEnd('character', end);
        selRange.select();
    } else if( field.setSelectionRange ) {
        field.setSelectionRange(start, end);
    } else if( field.selectionStart ) {
        field.selectionStart = start;
        field.selectionEnd = end;
    }
    field.focus();
}

describe('Text selection', function() {
    it('Selects text in a text area', function() {
        cy.get("#message").then(textarea => {
            createSelection(textarea, 0, 5);
        });
    }
}

Upvotes: 3

Related Questions