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

Cypress中如何对表单数值做四舍五入处理后执行断言校验

问题解决

错误根因

你遇到的toFixed is not a function报错核心原因有两个:

  • cy.get('#Client_rate_ap')返回的res是jQuery封装的DOM元素对象,不是元素内的数值,toFixed()是Number类型的专属方法,非数值类型调用自然会报错
  • 你页面元素的value使用逗号,作为小数分隔符,和JS默认的.小数分隔符不兼容,需要先做格式转换才能转为数值处理

正确实现代码

cy.get('#Client_rate_ap').then($el => {
  // 读取input元素的value属性
  const rawVal = $el.val()
  // 把逗号替换为JS识别的小数点,转为浮点数值
  const numVal = parseFloat(rawVal.replace(',', '.'))
  // 四舍五入保留2位小数后,把小数点换回逗号匹配你的场景
  const processedVal = numVal.toFixed(2).replace('.', ',')
  // 执行断言
  expect(processedVal).to.equal('11,13')
})

可选优化

如果多套系统都要用到这个处理逻辑,可以把它封装成Cypress自定义命令,避免重复写转换逻辑:

// 在cypress/support/commands.js中添加自定义命令
Cypress.Commands.add('assertRoundedDecimal', (selector, expectedVal, decimal = 2) => {
  cy.get(selector).then($el => {
    const rawVal = $el.val()
    const numVal = parseFloat(rawVal.replace(',', '.'))
    const processedVal = numVal.toFixed(decimal).replace('.', ',')
    expect(processedVal).to.equal(expectedVal)
  })
})

// 用例中直接调用即可
cy.assertRoundedDecimal('#Client_rate_ap', '11,13', 2)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 13:54:04