简体   繁体   中英

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.

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);
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM