如何用Protractor验证<button>元素禁用状态?element.isEnabled()失效怎么办?
Hey there! Let's work through your Protractor button validation questions step by step.
class="btn-blue"且包含disabled属性的按钮处于禁用状态 You have two reliable ways to confirm this button's disabled state:
Check the native
disabledattribute directly
HTML buttons only need the presence of thedisabledattribute to be disabled, regardless of its specific value. UsegetAttribute()to verify the attribute exists:const blueDisabledBtn = element(by.css('button.btn-blue')); expect(blueDisabledBtn.getAttribute('disabled')).not.toBeNull(); // For stricter validation, check for the exact attribute value: expect(blueDisabledBtn.getAttribute('disabled')).toBe('disabled');Use
isEnabled()with a negative assertion
Protractor'sisEnabled()method returnsfalsefor disabled elements, so you can directly assert this state:const blueDisabledBtn = element(by.css('button.btn-blue')); expect(blueDisabledBtn.isEnabled()).toBe(false);
If isEnabled() isn't behaving as expected for your mat-raised-button, it's usually tied to how Angular Material renders disabled states or timing issues with dynamic attribute binding. Try these solutions:
First, confirm your element locator is accurate
Make sure you're targeting the exact button with all its attributes:
const matDisabledBtn = element(by.css('button.btn-blue.mat-raised-button[type="button"]'));
Solution 1: Wait for the element to become unclickable (handles timing delays)
Angular Material might take a moment to apply the disabled attribute dynamically. Use Protractor's ExpectedConditions to wait for the button to be unclickable before asserting:
const EC = protractor.ExpectedConditions; const matDisabledBtn = element(by.css('button.btn-blue.mat-raised-button[type="button"]')); // Wait up to 5 seconds for the button to be unclickable (disabled) browser.wait(EC.not(EC.elementToBeClickable(matDisabledBtn)), 5000); expect(matDisabledBtn.isEnabled()).toBe(false);
Solution 2: Check for Angular Material's disabled class
Angular Material automatically adds the mat-button-disabled class to disabled buttons. You can verify this class exists as an alternative validation:
const matDisabledBtn = element(by.css('button.btn-blue.mat-raised-button[type="button"]')); expect(matDisabledBtn.getAttribute('class')).toContain('mat-button-disabled');
Solution 3: Evaluate the Angular binding (if you know the bound variable)
If your button's disabled state is bound to an Angular component variable (e.g., [disabled]="formIsInvalid"), you can directly check that variable's value:
const matDisabledBtn = element(by.css('button.btn-blue.mat-raised-button[type="button"]')); expect(matDisabledBtn.evaluate('formIsInvalid')).toBe(true);
内容的提问来源于stack exchange,提问作者Juan Pablo Arango

