0
0
Cypresstesting~5 mins

CSS assertions in Cypress

Choose your learning style9 modes available
Introduction

CSS assertions check if a webpage element looks right by testing its style. This helps catch design mistakes early.

To verify a button has the correct background color after a click.
To check if a text element uses the right font size and color.
To confirm that a hidden element is not visible on the page.
To ensure a layout change applies the correct margin or padding.
To test that a link changes color when hovered over.
Syntax
Cypress
cy.get('selector').should('have.css', 'property', 'value')

Use cy.get() to find the element by CSS selector.

have.css checks the CSS property and its expected value.

Examples
Checks if the button has a blue background color in RGB format.
Cypress
cy.get('button').should('have.css', 'background-color', 'rgb(0, 123, 255)')
Verifies the title text uses 24 pixels font size.
Cypress
cy.get('.title').should('have.css', 'font-size', '24px')
Confirms the menu is hidden by checking its display property.
Cypress
cy.get('#menu').should('have.css', 'display', 'none')
Sample Program

This test opens a sample page, finds the first button, and checks its background color and font size.

Cypress
describe('CSS Assertions Example', () => {
  it('checks button background color and font size', () => {
    cy.visit('https://example.cypress.io')
    cy.get('button').first().should('have.css', 'background-color', 'rgb(0, 123, 255)')
    cy.get('button').first().should('have.css', 'font-size', '14px')
  })
})
OutputSuccess
Important Notes

CSS property values are often returned in computed form, like RGB colors instead of hex.

Use browser DevTools to inspect exact CSS values before writing assertions.

Assertions fail if the element is not found or the CSS value does not match exactly.

Summary

CSS assertions test the style of webpage elements.

Use cy.get() with should('have.css') to check CSS properties.

Check colors, sizes, visibility, and layout styles to catch design issues early.