0
0
Cypresstesting~15 mins

CSS assertions in Cypress - Deep Dive

Choose your learning style9 modes available
Overview - CSS assertions
What is it?
CSS assertions are checks in automated tests that verify the styles of web elements, such as colors, fonts, sizes, and layouts. They help ensure that the visual appearance of a website matches the design requirements. Using Cypress, a popular testing tool, you can write tests that confirm CSS properties are correctly applied. This helps catch visual bugs early before users see them.
Why it matters
Without CSS assertions, visual bugs like wrong colors or misplaced elements can slip into production unnoticed, harming user experience and brand trust. CSS assertions let developers and testers catch these issues automatically, saving time and reducing manual checking. They make sure the website looks right on different devices and browsers, preventing costly redesigns or fixes later.
Where it fits
Before learning CSS assertions, you should understand basic CSS properties and how to select elements in Cypress tests. After mastering CSS assertions, you can explore visual regression testing and accessibility testing to improve overall UI quality.
Mental Model
Core Idea
CSS assertions are automated checks that confirm web elements have the correct visual styles by inspecting their CSS properties during tests.
Think of it like...
It's like checking the paint color and finish on a car before it leaves the factory to make sure it matches the customer's order exactly.
┌─────────────────────────────┐
│       Cypress Test          │
│  ┌───────────────────────┐ │
│  │ Select Element         │ │
│  │ Check CSS Property     │ │
│  │ Assert Expected Value  │ │
│  └───────────────────────┘ │
└───────────────┬─────────────┘
                │
                ▼
      Pass or Fail Test Result
Build-Up - 7 Steps
1
FoundationUnderstanding CSS Properties Basics
🤔
Concept: Learn what CSS properties are and how they control the look of web elements.
CSS properties include things like color, font-size, margin, padding, and display. Each property has a value that defines how the element appears. For example, 'color: red;' makes text red. Knowing these basics helps you know what to check in tests.
Result
You can identify which CSS properties affect the appearance you want to test.
Understanding CSS properties is essential because assertions check these exact values to confirm visual correctness.
2
FoundationSelecting Elements in Cypress Tests
🤔
Concept: Learn how to find and select HTML elements in Cypress to test their styles.
Cypress uses commands like cy.get() with CSS selectors to find elements. For example, cy.get('.button') selects elements with class 'button'. Selecting the right element is the first step before checking its CSS.
Result
You can target specific elements on the page to verify their styles.
Correct element selection ensures your CSS assertions check the intended parts of the UI.
3
IntermediateWriting Basic CSS Assertions
🤔Before reading on: do you think you can check any CSS property directly with Cypress commands? Commit to your answer.
Concept: Learn how to write assertions that check CSS properties using Cypress commands.
Use cy.get(selector).should('have.css', 'property', 'value') to assert CSS. For example, cy.get('.button').should('have.css', 'background-color', 'rgb(255, 0, 0)') checks if the button's background is red. Note that colors are often returned in rgb format.
Result
Tests pass if the element's CSS matches the expected value, fail otherwise.
Knowing the exact CSS value format (like rgb for colors) is key to writing correct assertions.
4
IntermediateHandling Dynamic and Computed Styles
🤔Before reading on: do you think CSS assertions always check the styles written in CSS files? Commit to your answer.
Concept: Understand that CSS assertions check the computed styles after all CSS and scripts apply, not just the raw CSS code.
Cypress reads the final computed style of elements, which includes styles from CSS files, inline styles, and JavaScript changes. For example, if JavaScript changes an element's color on hover, the assertion sees the updated color. This means tests reflect what users actually see.
Result
Assertions verify the real visual state, catching dynamic style changes.
Testing computed styles ensures your tests catch real user experiences, not just static code.
5
IntermediateBest Practices for CSS Assertions
🤔Before reading on: do you think asserting every CSS property is a good idea? Commit to your answer.
Concept: Learn which CSS properties to assert and how to write maintainable tests.
Focus on critical styles that affect usability and branding, like colors, fonts, and layout. Avoid asserting too many properties to keep tests fast and clear. Use variables or constants for expected values to ease updates. Also, prefer semantic selectors to avoid brittle tests.
Result
Tests are reliable, easy to maintain, and catch important visual bugs.
Selective assertions balance thoroughness and test stability, preventing flaky tests.
6
AdvancedTesting Responsive Styles with CSS Assertions
🤔Before reading on: do you think CSS assertions automatically check styles on different screen sizes? Commit to your answer.
Concept: Learn how to test CSS styles that change with screen size using Cypress viewport commands.
Use cy.viewport(width, height) to simulate different device sizes. Then assert CSS properties that should change, like font-size or display. For example, test that a menu is hidden on small screens by checking 'display: none'. This ensures your site looks good on all devices.
Result
Tests confirm responsive design works as expected across devices.
Simulating viewports in tests helps catch layout issues before real users find them.
7
ExpertAdvanced CSS Assertions with Custom Commands
🤔Before reading on: do you think you can simplify repeated CSS checks in Cypress? Commit to your answer.
Concept: Learn to create custom Cypress commands to reuse complex CSS assertions easily.
Define custom commands in Cypress to wrap common CSS checks. For example, create cy.assertButtonStyle() that checks multiple CSS properties for buttons. This reduces code duplication and improves readability. You can also add retries or custom error messages for better debugging.
Result
Your test code becomes cleaner, more maintainable, and easier to extend.
Custom commands empower you to build a robust testing framework tailored to your project's style needs.
Under the Hood
Cypress runs tests inside the browser, accessing the Document Object Model (DOM) directly. When you assert CSS properties, Cypress queries the computed styles of elements using the browser's window.getComputedStyle API. This returns the final styles after all CSS rules, inline styles, and JavaScript modifications are applied. Cypress then compares these values to your expected assertions and reports pass or fail.
Why designed this way?
Cypress was designed to run tests in the same environment as users see, ensuring accurate results. Using computed styles avoids false positives from raw CSS code that might be overridden or changed dynamically. This design choice makes tests reliable and reflective of real user experiences.
┌───────────────┐
│ Cypress Test  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Browser DOM   │
│ & CSS Engine  │
└──────┬────────┘
       │ getComputedStyle
       ▼
┌───────────────┐
│ Computed CSS  │
│ Properties    │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Assertion     │
│ Comparison    │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: do you think asserting 'color: red' works if the browser returns 'rgb(255, 0, 0)'? Commit yes or no.
Common Belief:You can assert CSS colors using the same color names as in CSS, like 'red'.
Tap to reveal reality
Reality:Browsers return computed colors in rgb or rgba format, so you must assert using these formats, e.g., 'rgb(255, 0, 0)'.
Why it matters:Using color names in assertions causes false test failures, wasting debugging time.
Quick: do you think CSS assertions check styles before JavaScript runs? Commit yes or no.
Common Belief:CSS assertions only check the styles defined in CSS files, ignoring JavaScript changes.
Tap to reveal reality
Reality:Assertions check computed styles after JavaScript runs, including dynamic style changes.
Why it matters:Ignoring dynamic styles can miss bugs where scripts change appearance unexpectedly.
Quick: do you think asserting every CSS property on an element is a good practice? Commit yes or no.
Common Belief:More CSS assertions mean better test coverage and fewer bugs.
Tap to reveal reality
Reality:Asserting too many properties makes tests slow and fragile, increasing maintenance overhead.
Why it matters:Over-asserting leads to flaky tests that break with minor unrelated style changes.
Quick: do you think CSS assertions automatically test responsive styles on all devices? Commit yes or no.
Common Belief:Once you write CSS assertions, they check styles on all screen sizes automatically.
Tap to reveal reality
Reality:You must explicitly change viewport sizes in tests to check responsive styles.
Why it matters:Failing to test responsiveness can let layout bugs slip into production on mobile devices.
Expert Zone
1
CSS property values can differ in format between browsers, so cross-browser testing with CSS assertions requires normalization or flexible matching.
2
Computed styles include inherited properties, so asserting a property might reflect a parent's style, not the element's own CSS rule.
3
Some CSS properties like transitions or animations change over time; asserting their values requires waiting or special handling to avoid flaky tests.
When NOT to use
CSS assertions are not suitable for full visual regression testing where pixel-perfect screenshots are needed. For that, use visual snapshot tools like Percy or Applitools. Also, avoid CSS assertions for complex animations or canvas-based graphics where styles are not directly accessible.
Production Patterns
In real projects, teams write CSS assertions for critical UI components like buttons, headers, and forms. They integrate these tests into CI pipelines to catch style regressions early. Custom Cypress commands and environment-specific style variables help maintain tests across themes and brands.
Connections
Visual Regression Testing
Builds-on
CSS assertions verify individual style properties, while visual regression testing compares full screenshots; knowing both gives a complete UI quality strategy.
Accessibility Testing
Complementary
CSS assertions ensure visual correctness, while accessibility testing ensures content is perceivable and operable; combining both improves user experience for all.
Quality Control in Manufacturing
Analogous process
Just like inspecting product features against specifications in factories, CSS assertions check web elements against design specs, highlighting universal quality assurance principles.
Common Pitfalls
#1Asserting CSS colors using color names instead of rgb values.
Wrong approach:cy.get('.btn').should('have.css', 'color', 'red')
Correct approach:cy.get('.btn').should('have.css', 'color', 'rgb(255, 0, 0)')
Root cause:Misunderstanding that browsers return computed colors in rgb format, not named colors.
#2Not setting viewport size before testing responsive styles.
Wrong approach:cy.get('.menu').should('have.css', 'display', 'none') // without viewport change
Correct approach:cy.viewport(320, 480) cy.get('.menu').should('have.css', 'display', 'none')
Root cause:Assuming tests run with default viewport simulate all device sizes automatically.
#3Asserting too many CSS properties causing fragile tests.
Wrong approach:cy.get('.card').should('have.css', 'margin', '10px').and('have.css', 'padding', '5px').and('have.css', 'border-radius', '4px').and('have.css', 'box-shadow', 'none')
Correct approach:cy.get('.card').should('have.css', 'margin', '10px').and('have.css', 'padding', '5px')
Root cause:Trying to cover every style detail instead of focusing on critical visual properties.
Key Takeaways
CSS assertions check the actual visual styles of web elements by inspecting their computed CSS properties during tests.
Using Cypress, you can write clear and maintainable CSS assertions that catch visual bugs early and improve UI quality.
Understanding how browsers compute and return CSS values, like colors in rgb format, is essential for writing correct assertions.
Testing responsive styles requires simulating different screen sizes explicitly in your tests.
Advanced techniques like custom Cypress commands help scale CSS assertions in large projects for better maintainability.