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

如何在Cypress中验证元素CSS高度仅保留两位小数?

解决Cypress验证CSS高度时忽略微小小数差异的问题

要只验证高度的前两位小数(即2.00),你可以自定义断言逻辑,先提取数值、处理小数位数后再比较,具体修改代码如下:

方法一:手动处理数值后断言

cy.get('.mat-card-content > mat-form-field:nth-of-type(2) div.mat-form-field-underline')
  .invoke('css', 'height') // 获取带px单位的height属性值
  .then(heightValue => {
    // 去掉px单位,转成数字后保留两位小数
    const parsedHeight = parseFloat(heightValue).toFixed(2);
    // 验证保留两位小数后的值是否为2.00
    expect(parsedHeight).to.equal('2.00');
  });

方法二:使用Cypress内嵌断言(更简洁)

cy.get('.mat-card-content > mat-form-field:nth-of-type(2) div.mat-form-field-underline')
  .should($el => {
    const height = parseFloat($el.css('height'));
    // 保留两位小数后和预期值比较
    expect(height.toFixed(2)).to.equal('2.00');
    // 也可选择数值比较(自动忽略末尾零的差异)
    // expect(Math.round(height * 100) / 100).to.equal(2.00);
  });

代码说明

  • invoke('css', 'height'):直接获取元素的height CSS属性值,返回带px的字符串(比如"2.0001628398895264px")
  • parseFloat(heightValue):剥离px单位,将字符串转为浮点数字
  • toFixed(2):将数字格式化为保留两位小数的字符串,自动处理四舍五入
  • 若偏好数值比较,可用Math.round(height * 100) / 100将数值取整到两位小数后,再和2.00做数值校验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 11:42:09