如何在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
相关产品推荐
相关产品推荐

