You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Cypress中获取任意元素的自定义CSS变量

在Cypress中获取并校验自定义CSS变量

当然可以,你可以通过浏览器原生的getComputedStyle()方法,在Cypress中直接获取元素的自定义CSS变量值,无需校验转换后的具体样式(比如RGB值),下面是几种实用的实现方式:

方法一:获取全局根元素的CSS变量

如果你的CSS变量定义在:root全局作用域,比如:

:root {
  --primary-text-color: #000000;
  --base-spacing: 16px;
}

可以用以下代码获取并校验:

cy.window().then((win) => {
  const rootStyle = win.getComputedStyle(win.document.documentElement);
  const primaryTextColor = rootStyle.getPropertyValue('--primary-text-color').trim();
  expect(primaryTextColor).to.equal('#000000');
});

方法二:获取特定元素的CSS变量

如果变量是绑定在某个具体元素上的,比如:

.card {
  --card-bg-color: #f5f5f5;
}

定位到元素后直接读取其计算样式:

cy.get('.card').then(($el) => {
  const elementStyle = window.getComputedStyle($el[0]);
  const cardBgColor = elementStyle.getPropertyValue('--card-bg-color').trim();
  expect(cardBgColor).to.equal('#f5f5f5');
});

方法三:封装自定义命令提升复用性

如果需要多次校验CSS变量,可以在cypress/support/commands.js中封装自定义命令:

Cypress.Commands.add('getCssVariable', (selector, variableName) => {
  return cy.get(selector).then(($el) => {
    const style = window.getComputedStyle($el[0]);
    return style.getPropertyValue(variableName).trim();
  });
});

之后在测试用例中直接调用:

cy.getCssVariable('.card', '--card-bg-color').should('equal', '#f5f5f5');

内容的提问来源于stack exchange,提问作者Stefanie Uhl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 21:50:23