Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protractor - see text on page

I'm trying to write a test in Protractor, without highly coupling my test to specific markup of the page.

For example, given a typical log in page I'd want to test that if incorrect credentials are provided, an error message appears.

The way that my markup would display that error is:

<div class="alert alert-danger">
    <ul>
        <li>Invalid username or password.</li>
    </ul>
</div>

This unordered list may contain other errors, too - so I don't want to make an assertion on the list element itself. In any case, I may decide to move away from displaying the error as a list, and may want to show it in some other way.

All I want is to be able to assert that the page contains: Invalid username or password.

I'd like to be able to do something like:

expect(page.getContents()).to.contain('Invalid username or password.'); 

But of course this doesn't work.

Are there any methods available in Protractor that can allow me to do this?

like image 999
Amo Avatar asked Nov 13 '15 10:11

Amo


3 Answers

You can use element.getText().

https://angular.github.io/protractor/#/api?view=webdriver.WebElement.prototype.getText :

Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.

To get all the text from your list. And then expect(text).toContain("Invalid username or password")

example using angularjs.org:

 browser.driver.get('https://angularjs.org/')
    el = element(by.css('.first'))
    el.getText().then(function(text){expect(text).toContain("AngularJS is a toolset for")});
like image 98
cvakiitho Avatar answered Nov 15 '22 12:11

cvakiitho


You can use xPath to select the DOM element that contains the text you are looking for and, then, check if this element exists.

I'm using this code and

var myText = "Invalid username or password.";
var selectedElement = element(by.xpath("//*[. = '" + myText + "']"));

expect(selectedElement.isPresent()).to.eventually.equal(true, "This text is not present in page.").and.notify(callback);

I've tested the snippet on your example and works. Note, I'm using chai-as-promised, so, if you don't recognize the sintax don't worry. The important thing is that the second part: expect(selectedElem)... is used to check if the element is present in page.

like image 42
Ema.jar Avatar answered Nov 15 '22 11:11

Ema.jar


This works for me:

expect(element(by.cssContainingText('*', 'Invalid username or password.')).isPresent()).toBeTruthy();
like image 25
user2878850 Avatar answered Nov 15 '22 11:11

user2878850