tealang
tealang

Reputation: 201

protractor: How to find element by exact text?

testing applications encountered another problem. I need to click element by exact text, so i found a solution where I use cssContainingText and each,then if statment to comapre text and select certain element, but I think maybe is a better solution for that purpous?

Second questions: somewhere on stackoverflow I read that

element.click().then(){
dosomething;
});

will cause that 'dosomething;' will perform after click, I try this and it doesn't work, how to make that 'dosomething;' will perform after click;

Upvotes: 11

Views: 18120

Answers (4)

Yosra Saadallah
Yosra Saadallah

Reputation: 61

 const allOptions = element.all(by.css('css-class'));
            allOptions.filter( (elem) => {
                return elem.getText().then((text) => {
                    return exact-text === text;
                });
            }).first().click();

Upvotes: 0

Martin Sznapka
Martin Sznapka

Reputation: 819

1) Delian has correct answer, but in many cases the element content has additional whitespaces, so you need to trim them:

getElementsByText: function (text, parentXpathSelector) {
    parentXpathSelector = parentXpathSelector || '//';
    return element(by.xpath(parentXpathSelector + '*[normalize-space(text())="' + text + '"]'));
}

2) https://stackoverflow.com/a/21785088/3147680

Upvotes: 5

Jens Alenius
Jens Alenius

Reputation: 1931

Xpath is elegant but not so easy to read if someone else needs look at the code. I often pick an element in a repeater by only using cssContainingText and chained by.css. example:element(by.css('.dropdown-menu')).element(by.cssContainingText('span', constants.STATUS.PENDING)).click(); sure it might be slower than xpath. I realy don't now. But managable comes first

Upvotes: 0

Delian Mitankin
Delian Mitankin

Reputation: 3691

You can use by.xpath as a selector:

By exact text

element(by.xpath('.//*[.="text"]'))

By css class with exact text

element(by.xpath('.//*[.="text" and class="some-css-class"]'))

You can find a lot of xpath examples online. There's also a tester you can use.

Upvotes: 20

Related Questions