Rohr Facu
Rohr Facu

Reputation: 737

Get selected option text in protractor

I'm trying to get the selected text of a select, and compare the value within an expect. I have the following code:

expect<any>(select_seller.getText()).toEqual('SELLER 1')

But what I got as result is the text of the whole list of sellers, as follows:

Expected ' SELLER 2
SELLER 1
SELLER 3
SELLER 4
 ' to equal 'SELLER 1'.

What I've tried:

EDIT:

The html code for the select is:

<select id="field_seller" [(ngModel)]="o.seller">
  <option [ngValue]="sellerOption" *ngFor="let sellerOption of sellers">
      {{sellerOption.name}}
  </option>
</select>

Anyone has an idea on this? Thanks a lot!!

Upvotes: 1

Views: 2257

Answers (1)

demouser123
demouser123

Reputation: 4264

This might be not correct because I've haven't tested this yet but you can do something like

function getSelectedText(select) {
  return select.getAttribute('value')
    .then(function (i) {
      return select.element(by.css('option[value="' + i + '"]')).getText();
    });
}

getSelectedText(element(by.id('select_id'))).then(...)

Or more simple way:

function getSelectedText(select) {
    return select.element(by.css('option:checked')).getText();
}

getSelectedText(element(<locator of select>)).then(...)

Upvotes: 5

Related Questions