Expect selected text

I can simulate text selection with protractor by a lot of different ways. But I can't find solution how I can expect that text was really selected. How I can do this without using marking?

I can simulate select text by protractor with:

  1. DragAndDrop function (mouse)
  2. Combination: browser.actions().sendKeys(protractor.Key.CONTROL, 'a').perform();
  3. Combination: shift + left arrow

Upvotes: 3

Views: 1510

Answers (2)

deekshith
deekshith

Reputation: 23

Here you might also need to verify that the text inside a particular text box is selected. You can do that by using these 2 lines below:

*document.evaluate( 'XpathOfTheElement//input', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue.selectionStart
document.evaluate( 'XpathOfTheElement//input', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue.selectionEnd*

if 'in' is selected in the string 'testing' then first line will return 4 and second line will return 6.

Upvotes: 2

alecxe
alecxe

Reputation: 474151

Elaborating Michael's comment into a working example.

In the following demo example, we are navigating to the AngularJS website, sending "testing" text to the search input on the top right, pressing left arrow 3 times to move the cursor 3 characters to the left, then pressing SHIFT + ARROW_RIGHT keyboard combination 2 times to select the next 2 characters - which is in: enter image description here

Finally, we are applying the solution to get the selection text provided here and asserting:

describe("Get selection text", function () {
    beforeEach(function () {
        browser.get("https://angularjs.org/");
    });

    it("should input 'testing', select 'in' and assert it is selected", function () {
        var q = element(by.name("as_q"));

        // enter 'testing' and go 3 chars left
        q.sendKeys("testing")
            .sendKeys(protractor.Key.ARROW_LEFT)
            .sendKeys(protractor.Key.ARROW_LEFT)
            .sendKeys(protractor.Key.ARROW_LEFT);

        // select 2 chars to the right
        browser.actions()
            .keyDown(protractor.Key.SHIFT)
            .sendKeys(protractor.Key.ARROW_RIGHT)
            .sendKeys(protractor.Key.ARROW_RIGHT)
            .keyUp(protractor.Key.SHIFT)
            .perform();

        // get highlighted text
        var highligtedText = browser.executeScript(function getSelectionText() {
            var text = "";
            if (window.getSelection) {
                text = window.getSelection().toString();
            } else if (document.selection && document.selection.type != "Control") {
                text = document.selection.createRange().text;
            }
            return text;
        });

        expect(highligtedText).toEqual("in");
    });
});

Hope this would help you and others coming here.

Upvotes: 4

Related Questions