如何从测试中的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
相关产品推荐
相关产品推荐

