0
0
CypressHow-ToBeginner ยท 3 min read

How to Assert Element Has Class in Cypress: Simple Guide

In Cypress, you can assert that an element has a specific class using .should('have.class', 'className'). This checks if the element's class list includes the given class name during test execution.
๐Ÿ“

Syntax

The basic syntax to assert an element has a class in Cypress is:

  • cy.get(selector): Selects the element(s) using a CSS selector.
  • .should('have.class', 'className'): Asserts the element has the specified class.
javascript
cy.get('selector').should('have.class', 'className')
๐Ÿ’ป

Example

This example shows how to check if a button with id submit-btn has the class active. The test will pass if the class is present, otherwise it fails.

javascript
describe('Class Assertion Example', () => {
  it('checks if button has active class', () => {
    cy.visit('https://example.cypress.io')
    cy.get('#submit-btn').should('have.class', 'active')
  })
})
Output
Test passes if #submit-btn has class 'active'; fails otherwise.
โš ๏ธ

Common Pitfalls

Common mistakes include:

  • Using .should('have.class', 'class1 class2') with multiple classes at once, which fails because it expects exactly one class.
  • Selecting the wrong element or using an incorrect selector, causing the assertion to fail.
  • Not waiting for the element to appear or update its classes before asserting.

Always assert one class at a time and ensure the element is visible or exists before checking.

javascript
/* Wrong: multiple classes in one assertion */
cy.get('.my-element').should('have.class', 'class1 class2')

/* Right: assert classes separately */
cy.get('.my-element').should('have.class', 'class1')
cy.get('.my-element').should('have.class', 'class2')
๐Ÿ“Š

Quick Reference

CommandDescription
cy.get('selector')Select element(s) by CSS selector
.should('have.class', 'className')Assert element has the specified class
.should('not.have.class', 'className')Assert element does NOT have the specified class
โœ…

Key Takeaways

Use cy.get(selector).should('have.class', 'className') to check for a class.
Assert one class at a time; multiple classes in one assertion cause failure.
Ensure the element exists and is visible before asserting its class.
Use .should('not.have.class', 'className') to check absence of a class.
Correct selectors are crucial for reliable assertions.