0
0
CypressHow-ToBeginner ยท 3 min read

How to Assert CSS Property in Cypress Tests Easily

In Cypress, you can assert a CSS property using cy.get() to select the element and .should('have.css', 'property', 'value') to check the CSS value. This lets you verify styles like colors, fonts, or sizes directly in your tests.
๐Ÿ“

Syntax

Use cy.get(selector) to find the element, then chain .should('have.css', 'property', 'value') to assert the CSS property and its expected value.

  • selector: CSS selector to find the element.
  • property: The CSS property name as a string (e.g., 'color').
  • value: The expected CSS value as a string (e.g., 'rgb(255, 0, 0)').
javascript
cy.get('selector').should('have.css', 'property', 'value')
๐Ÿ’ป

Example

This example checks if a button with class .submit-btn has a background color of blue.

javascript
describe('CSS Property Assertion', () => {
  it('checks button background color', () => {
    cy.visit('https://example.cypress.io')
    cy.get('.submit-btn').should('have.css', 'background-color', 'rgb(0, 0, 255)')
  })
})
Output
Test passes if the button's background color is blue; otherwise, it fails.
โš ๏ธ

Common Pitfalls

Common mistakes include:

  • Using incorrect CSS property names (e.g., 'bg-color' instead of 'background-color').
  • Expecting color values in hex format when Cypress returns RGB strings.
  • Not waiting for the element to be visible or rendered before asserting.

Always check the exact CSS value format by inspecting the element in browser DevTools.

javascript
/* Wrong way: expecting hex color */
cy.get('.submit-btn').should('have.css', 'background-color', '#0000ff')

/* Right way: use RGB format */
cy.get('.submit-btn').should('have.css', 'background-color', 'rgb(0, 0, 255)')
๐Ÿ“Š

Quick Reference

CommandDescriptionExample
cy.get(selector)Selects an element by CSS selectorcy.get('.btn')
should('have.css', property, value)Asserts the CSS property valueshould('have.css', 'color', 'rgb(255, 0, 0)')
Common CSS propertiesProperties you can check'color', 'background-color', 'font-size', 'display'
โœ…

Key Takeaways

Use cy.get() with should('have.css', property, value) to assert CSS styles.
CSS values like colors are returned in RGB format, not hex.
Check the exact CSS property name and value format in browser DevTools.
Wait for elements to be visible before asserting CSS properties.
Common CSS properties to check include color, background-color, font-size, and display.