0
0
CypressHow-ToBeginner ยท 3 min read

How to Assert Element Disabled in Cypress: Simple Guide

In Cypress, you can assert that an element is disabled by using cy.get(selector).should('be.disabled'). This checks if the element has the disabled attribute or is otherwise disabled in the UI.
๐Ÿ“

Syntax

The basic syntax to assert an element is disabled in Cypress is:

  • cy.get(selector): Finds the element using a CSS selector.
  • .should('be.disabled'): Asserts the element is disabled.
javascript
cy.get('button#submit').should('be.disabled')
๐Ÿ’ป

Example

This example shows how to check if a button with id submit is disabled on the page.

javascript
describe('Button Disabled Test', () => {
  it('checks if submit button is disabled', () => {
    cy.visit('https://example.com')
    cy.get('button#submit').should('be.disabled')
  })
})
Output
Test passes if the button with id 'submit' is disabled; fails otherwise.
โš ๏ธ

Common Pitfalls

Common mistakes when asserting disabled elements in Cypress include:

  • Using .should('have.attr', 'disabled') which only checks the attribute but not if the element is truly disabled.
  • Not waiting for the element to appear before asserting, causing flaky tests.
  • Using incorrect selectors that do not target the intended element.

Always prefer .should('be.disabled') for a reliable check.

javascript
/* Wrong way: only checks attribute presence, not actual disabled state */
cy.get('button#submit').should('have.attr', 'disabled')

/* Right way: checks if element is disabled in UI */
cy.get('button#submit').should('be.disabled')
๐Ÿ“Š

Quick Reference

AssertionDescription
should('be.disabled')Checks if element is disabled in UI
should('not.be.disabled')Checks if element is enabled
should('have.attr', 'disabled')Checks if disabled attribute exists (less reliable)
โœ…

Key Takeaways

Use cy.get(selector).should('be.disabled') to assert an element is disabled.
Avoid only checking the disabled attribute; prefer 'be.disabled' for accuracy.
Ensure your selector correctly targets the element before asserting.
Wait for elements to load to prevent flaky tests.
Use 'should('not.be.disabled')' to check if elements are enabled.