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
| Command | Description | Example |
|---|---|---|
| cy.get(selector) | Selects an element by CSS selector | cy.get('.btn') |
| should('have.css', property, value) | Asserts the CSS property value | should('have.css', 'color', 'rgb(255, 0, 0)') |
| Common CSS properties | Properties 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.