Protractor Chained Elements by Using Variables?

前端 未结 3 647
半阙折子戏
半阙折子戏 2020-12-16 01:39

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:

v         


        
相关标签:
3条回答
  • 2020-12-16 01:58

    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();
    
    0 讨论(0)
  • 2020-12-16 02:01

    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('...');
    
    0 讨论(0)
  • 2020-12-16 02:03

    I wanted to mention that using 5.2.2 version this implementation is bit different. To get actual selector value you must use following code

    let selector = child.locator().value
    

    This is because locator returns an object which contains selector and other properties, but in this case, you only need selector. here is what is returned by method locator()

    name(name) {
      return By.css('*[name="' + escapeCss(name) + '"]');
    }
    { using: 'css selector', value: '.child-class' }
    

    Here is how it should be implemented now.

    var parent = element(by.css('.parent-class'));
    var child = element(by.css('.child-class'));
    parent.element(child.locator().value).getText();
    
    //short hand
    var parent = $('.parent-class');
    var child = $('.child-class')
    
    parent.$(child.locator().value).getText();
    
    0 讨论(0)
提交回复
热议问题