Protractor - How to get first or last CHILD value

2.5k views Asked by At

I have some HTML which looks like this:

<div class="label label-primary ng-scope" ng-if="vehicle.manufacturerCode">
   <strong class="ng-binding">AUDI</strong>
   <small class="ng-binding">[00]</small>
   <span class="btn btn-flat" ng-click="axCarSearch.removeIdentification(1, $event)">
      <span class="glyphicon glyphicon-remove-sign"></span>
   </span>
</div>

From this HTML i need to get values of first or last ng-binding. I can imagine I can get to vehicle.manufacturerCode with something like:

element(by.css('[ng-if="vehicle.manufacturerCode"]'));

But not sure how i can go deeper and get string "AUDI" or string "[00]" to compare if they are equal.

It may looks like:

it('Compare results ', function() {
    var manufacturer = element(by.css('[ng-if="vehicle.manufacturerCode"]')).child[0];
    expect(manufacture.toEqual('AUDI');
});
2

There are 2 answers

6
alecxe On BEST ANSWER

The HTML you've provided suggests by.binding locators can be used, but you haven't provided the actual bindings - you can see them in the non-rendered HTML source code, e.g. should be smth like:

<strong class="ng-binding">{{ vehicle.manufacturer }}</strong>

In this case, you could've located the desired elements this way:

var div = element(by.css('[ng-if="vehicle.manufacturerCode"]'));

var name = div.element(by.binding("vehicle.manufacturer"));
var code = div.element(by.binding("vehicle.manufacturerCode"));

expect(name.getText()).toEqual("AUDI");
expect(code.getText()).toEqual("[00]");    

From what you've provided, you can chain the element calls and rely on the tag names:

var div = element(by.css('[ng-if="vehicle.manufacturerCode"]'));

var strong = div.element(by.tagName("strong"));
var small = div.element(by.tagName("small"));

expect(strong.getText()).toEqual("AUDI");
expect(small.getText()).toEqual("[00]");

Note that, in general, relying on ng-if and tag names is not quite reliable.

0
Nikhil Batra On
$('.label-primary').children().each(function () {
    //Use value here using $this
});

Use each loop to iterate all the children of the div.