Search code examples
javascriptangularjstestingprotractorend-to-end

How to return child elements from within parent element in Protractor


I'm looking for a way to return the child elements from within a given parent element block (using page objects), and to be able to call them via chaining. For example, given a number of widgets on a page:

<div id="widget-1">
  <div class="name">Widget 42</div>
  <div class="color">Blue</div>
</div>
<div id="widget-2">
  <div class="name">Widget 23</div>
  <div class="color">Red</div>
</div>

And a page object, widgetPage:

this.widget = function(num) { return $('div#widget-' + num) };

I want to ONLY grab the name and color from the first widget block. This works in my spec:

expect(widgetPage.widget('42').$('color').getText()).toBe('Blue');

But I don't want to have selector code in my spec; I want it in the page object, where it belongs. I've not been able to find a good way to do this. I've tried various things like...

this.getWidgetElms = function(num) {
    return this.widget(num).then(function(w) {
        return {
            name: w.$('div.name'),
            color: w.$('div.color')
        };
    });
};
// fails because name and color are undefined... 

Ultimately, I'm looking to be able to do something like this (not working):

expect(widgetPage.getWidgetElms('42').color.getText()).toBe('Blue');

Obviously I'm doing something wrong... How can I return only the child elements for the first widget block?


Solution

  • What if you would return an object out of the widget function:

    this.widget = function (num) {
        var elm = element(by.css('div#widget-' + num));
        return {
            widget: elm,
            name: elm.element(by.css('div.name')),
            color: elm.element(by.css('div.color'))
        };  
    };
    

    Then, in your spec:

    var widget = widgetPage.widget('42');
    expect(widget.name.getText()).toBe('Widget 42');
    expect(widget.color.getText()).toBe('Blue');