Check text in a DOM element using Protractor

2019-07-21 10:33发布

问题:

Here’s what I’m trying to do while testing an Angular app with Protractor. I would like to get a certain element, which is somewhat like this:

<div class="someClass">
   <p>{{textFromBoundModel}}</p>
</div>

then get its html, and check whether it contains the text that I expect it to have.

I tried to get this element first by the cssContainingText method, but it didn't quite work (not sure why; maybe because the text within the paragraph is produced dynamically). So now I’m getting this element using just the by.css locator. Next, I'm checking whether it contains the text I’m testing for:

// this is Cucumber.js    

this.Then(/^Doing my step"$/, function(callback){
    var el = element(by.css('.someClass'));            
    expect(el).to.contain("some interesting string");
    callback();
 });
});

but this doesn't work. Problem is, el is some kind of a locator object, and I can’t figure out how to get html of the element it found in order to test against this html. Tried .getText(), with no success.

Any suggestions?

回答1:

Does:

expect(el.getText()).to.eventually.contain("some interesting string");

work?

I believe you need the .eventually to wait for a promise to resolve, and you need the .getText() to get at the content of the div.

See the chai-as-promised stuff at the head of the cucumber sample.