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

如何从测试中的calc函数返回值提取百分比数值?

解决方法

方法1:提取calc表达式中的百分比数值

利用正则匹配固定格式的calc()字符串,从中提取百分比数字:

it("has resizable containers", async () => {
  const initialRightWidth = rightContainer.style.width;
  // 匹配calc(x% - ypx)格式,捕获百分比数值
  const percentageMatch = initialRightWidth.match(/calc\((\d+)% - \d+px\)/);
  // 对比百分比数字
  expect(percentageMatch[1]).toEqual("50");
  // 或者拼接成百分比字符串对比
  // expect(`${percentageMatch[1]}%`).toEqual("50%");
});

方法2:获取元素实际渲染的像素宽度

如果需要验证真实渲染的宽度而非CSS表达式,使用getBoundingClientRect()获取实际计算值:

it("has resizable containers", async () => {
  const rect = rightContainer.getBoundingClientRect();
  // 根据父容器宽度计算预期值,比如父容器宽1000px的话,预期为496px(50% -4px)
  expect(rect.width).toBeCloseTo(496);
});

方法3:CSS值解析工具(可选)

若calc()格式可能变化,可使用CSS解析库提取值(需先安装依赖):

// 安装依赖:npm install css-value --save-dev
import parseCssValue from 'css-value';

it("has resizable containers", async () => {
  const initialRightWidth = rightContainer.style.width;
  const parsedValue = parseCssValue(initialRightWidth);
  // 提取百分比部分的数值
  expect(parsedValue.value[0].value).toEqual(50);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 06:46:06