Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protractor Chained Elements by Using Variables?

Tags:

protractor

I am trying to keep my pageObjects in Protractor as clean as possible, but have run up against some behavior in selecting sub-elements.

This works:

var parent = element(by.css('.parent-class'));

parent.element(by.css('.child-class')).getText();

However this does not:

var parent = element(by.css('.parent-class'));
var child = element(by.css('.child-class'));

parent.child.getText();

Is there someway to do something like the second example? I'd rather not have the element locators spread throughout the methods on my pageObjects, but it seems thats the only way to locate subelements?

In actual application I have a long list of cards, from which I filter down to just the one I am looking for. I then want to do things with subelements of the card.

like image 335
mollons Avatar asked May 18 '15 17:05

mollons


2 Answers

You could use the locator() function to get the locator of the child element and use it to find a child of the parent. This is similar to the solution you provided in your comment, but allows you to define all properties on your page object as web elements instead of a mix of elements and locators:

var parent = element(by.css('.parent-class'));
var child = element(by.css('.child-class'));

parent.element(child.locator()).getText();
like image 191
Nathan Thompson Avatar answered Feb 09 '23 16:02

Nathan Thompson


I have a lot of the following code:

var parent = element(by.css('.parent-class'));
var child = parent.element(by.css('.child-class'));

child.getText();

But as far as I understood you have a lot of children and you don't want to list all the variants.

Additionally to Nathan Thompson answer you can have a helper function in page object to find subelement:

function getCard(parent, child) { // Or getChild()
  return element(by.css(parent)).element(by.css(child));
}

function getCardText(parent, child) { // Or getChildText
  return getCard(parent, child).getText();
}

So then you can just write in spec:

expect(cardPage.getCardText('.parent-class', '.child-class')).toBe('...');
like image 45
Igor Shubovych Avatar answered Feb 09 '23 16:02

Igor Shubovych