Pratik Gadoya
Pratik Gadoya

Reputation: 1511

How can I check button has class disabled?

I have two buttons. If one button has class disable than other hasn't. Now I want to check that if first button has class disable than I need to click on second button and vice-versa.

I am trying with below code but it is returning every time true. Disable class is added dynamically depends on condition.

if (expect(element(by.css('ul#menu [data-selector="holdInventory"]'))
.getAttribute('class')).toEqual('disabled')) {
    console.log('has class');
} else {
    console.log('has not class');
}

Any help will appreciated.

Upvotes: 1

Views: 1637

Answers (3)

Rakesh
Rakesh

Reputation: 329

In protractor everything is a promise. So in order to perform an operation you need to resolve it first and then validate the class value. Also you cannot use equal because an element can be associated with multiple classes so you need to make use of includes instead.

var btn1 = element(by.css('ul#menu [data-selector="holdInventory"]'));
btn1.getAttribute('class')).then(function(cls) {
  if(cls.includes('disabled')) {
    btn1.click();
  } else {
    btn2.click();
  }
});

Upvotes: 2

Dhaval Chheda
Dhaval Chheda

Reputation: 924

You can use ng-class to add class of disable dynamically with some condition like this

<button ng-class="{'disable' : switchDisable == '1'}"> Disable </button>
<button ng-class="{'disable' : switchDisable == '0'}"> Not Disable</button>

Here switchDisable Is a scope value which you can toggle on click of the button like $scope.switchDisable = 1 or you can use any other expression as you like. Reference : https://docs.angularjs.org/api/ng/directive/ngClass

Upvotes: 0

Aravind
Aravind

Reputation: 41571

You can check the length is 1 of the elements by querying all as below,

let  elements = fixture.debugElement.queryAll(By.css('ul#menu [data-selector="holdInventory"]');
expect(elements.length).toEqual(1); ////////////// 

Upvotes: 0

Related Questions