KMK
KMK

Reputation: 1509

Error when trying to get single item from element.all in Protractor

I have the following test code (a simplified example):

e = element(by.id('element-id'));

it('description', function(){
    e.all(by.tagName('my-directive')).then(function(items){
        expect(items.count()).toEqual(3); //error
        expect(items.length).toEqual(3); //ok
        expect(items.get(0).getAttribute('my-attr')).toEqual('1'); //error
    });
});

This is the HTML:

<div id="element-id">
    <my-directive my-attr="1"></my-directive>
    <my-directive my-attr="0"></my-directive>
    <my-directive my-attr="0"></my-directive>
</div>

When I run this test I get the following error:

TypeError: undefined is not a function

I stripped it down and found out that the error is from the get() function and the count() function. I have read about the functions in the Protractor API and used them the same way as the example on the site, so I don't understand why it does not work for me.

Does anyone know what I'm doing wrong?

I have also tried this (included 'element'):

e.element.all(by.tagName('my-directive')).then(function(items){...})

But that gave an error event without the get() function.

Upvotes: 1

Views: 1674

Answers (1)

Olov
Olov

Reputation: 1203

items in this case is just an ordinary array. You get

TypeError: undefined is not a function

because there isn't any function on the Array.prototype called count.

count() and get() can only be called on ElementFinderArrays, which is a Protractor specific object: http://angular.github.io/protractor/#/api?view=ElementArrayFinder

If you want to get the length and one of the elements' attribute, this will work:

e.all(by.tagName('my-directive')).then(function(items){
    expect(items.length).toEqual(3);
    expect(items[0].getAttribute('my-attr')).toEqual('1');
});

or like this:

expect(e.all(by.tagName('my-directive')).count()).toEqual(3);
expect(e.all(by.tagName('my-directive')).get(0).getAttribute('my-attr')).toEqual(1);

Upvotes: 4

Related Questions