This guide shows you how to verify that your web app correctly changes CSS custom properties (variables) at runtime, using Cypress. You’ll learn to assert computed style values, handle asynchronous updates, and avoid flaky tests. No prior Cypress experience is required beyond basic test setup.
What You’ll Need
- A project with Cypress installed (npm install cypress –save-dev)
- An app that changes CSS variables via JavaScript (e.g., theme toggles, dynamic styling)
- Basic familiarity with CSS custom properties syntax (–var-name: value)
Step-by-Step
-
Identify the target element and variable.
Determine which element holds the CSS variable you want to test. It could be on the:root, a container, or a specific component. Use your browser’s DevTools to inspect the element and confirm the variable name (e.g.,--primary-color). -
Write a test that triggers the change.
In your Cypress spec file, usecy.visit()to load the page, then interact with the UI that changes the variable—click a theme toggle, submit a form, or call a method viacy.window(). For example:cy.get('button.theme-toggle').click(). -
Use
cy.get()to target the element.
After the interaction, get the element that holds the variable. If it’s on:root, you can usecy.get('html')orcy.get(':root'). For a container, use its selector. Ensure the element is visible and in the DOM. -
Read the computed style with
invoke('css', '--variable-name').
Cypress’s.invoke()can access the CSS property value. The command returns the computed value as a string. For example:cy.get('html').invoke('css', '--primary-color').should('eq', '#ff0000'). This works because Cypress uses the browser’sgetComputedStyle. -
Handle CSS variable inheritance.
If the variable is set on a parent but you’re testing a child, the child inherits it. You can still read it from the child, but be aware that the value might be the inherited one. To test the actual definition, target the element where it’s defined. -
For asynchronous changes, use
cy.should()with a callback.
If the variable changes after a network request or animation, use a retry-able assertion. Instead ofinvoke().should(), you can usecy.get('html').should('have.css', '--primary-color', '#ff0000'). This automatically retries until the value matches or times out. -
Test the absence or reset of a variable.
To verify a variable is removed or reset, check that the computed value is the initial or inherited value. For example,cy.get('html').invoke('css', '--spacing').should('eq', '0px')if the default is 0. -
Use custom Cypress commands for reuse.
If you test many variables, create a custom command likeCypress.Commands.add('assertCssVar', (selector, varName, value) => { ... })to keep your tests DRY.
Common Mistakes
- Using
cy.get().should('have.attr', 'style')—this checks the inline style attribute, not the computed style. CSS variables set in stylesheets won’t appear there. - Forgetting to wait for the change—if the variable updates after an animation or API call, your assertion may run too early. Use
cy.should()with a timeout orcy.wait()for known delays. - Targeting the wrong element—CSS variables are inherited, so reading from a child might give a value that’s not what you expect. Always test on the element where the variable is actually defined.
- Assuming the value format—CSS variables are strings. A color like
#ff0000might be returned asrgb(255, 0, 0)in some browsers. Use the exact string you expect fromgetComputedStyle. - Not resetting state between tests—if one test changes the variable and the next doesn’t reset it, tests become order-dependent. Use
beforeEachto reload the page.
Tips
- Use
cy.pause()to debug—it lets you inspect the app state before the assertion runs. - Log the computed value in your test with
cy.log()orconsole.loginside a.then()to see what the browser actually returns. - For complex values like gradients or shadows, compare against the full computed string, which may include spaces or commas in a specific format.
- If you’re testing theme switching, consider using a data attribute (e.g.,
data-theme) alongside the CSS variable, and assert on that attribute as a simpler, more stable check. - Keep your test selectors stable—avoid relying on deeply nested CSS classes that might change.
Troubleshooting
- Assertion fails even though the variable looks correct in DevTools. This is usually a timing issue. Increase the timeout:
cy.get('html', { timeout: 10000 }).should('have.css', '--var', 'value'). - Value returned is
undefinedor empty. This means the variable is not set on that element. Check if it’s on a parent, or if the variable name is misspelled (including the double dash). - Value differs in format (e.g.,
rgb()vs hex). Use the exact string fromgetComputedStyle—open DevTools, rungetComputedStyle(document.documentElement).getPropertyValue('--var')in the console to see the actual value. - The test passes in headed mode but fails in headless. Headless browsers may have different default font sizes or rendering. Ensure your variable is not dependent on viewport size or media queries that differ.
- Using
cy.invoke('css', '--var')throws an error. This can happen if the element is not attached to the DOM. Ensure the element exists withcy.get()first, and that it’s visible.
Frequently Asked Questions
Can I test CSS variables using cy.get().should('have.css', ...)?
Yes, that works for CSS custom properties. The have.css assertion uses getComputedStyle under the hood, so it reads the actual computed value.
What if the variable is set on :root but I’m testing a child element?
You can read the variable from the child because it inherits, but to verify the definition itself, target :root or html.
How do I wait for a CSS variable to change after an animation?
Use cy.should('have.css', '--var', 'expected')—Cypress retries the assertion until it passes or times out. You can also set a custom timeout.
Why is my color variable returned as rgb(255, 0, 0) instead of #ff0000?
Browsers normalize colors in computed styles. Use the exact string from getComputedStyle in your assertion, or convert both to a common format.
Can I test CSS variables in iframes?
Yes, but you need to access the iframe’s document. Use cy.iframe() from a plugin like cypress-iframe, or use cy.get('iframe').its('contentDocument.body') to get the element.
Is there a way to test that a CSS variable is NOT set?
Check that the computed value is the initial/inherited value. For example, if the default is 0px, assert that. There’s no direct ‘not have css’ assertion, but you can use .should('not.have.css', '--var', 'unexpectedValue').
Related
General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.
More in this bed
- How to Check Your Linux Kernel for Spectre
- iPhone Safe Mode: How to Enable or Disable It
- Fix Slow Internet Lag on Samsung Galaxy Note
- iOS 18 Safari Not Working? Fixes That Help
- How to Get iOS 17 on iPhone X (Safe Methods)
- Fix Gmail IMAP Error in Outlook: Step-by-Step