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

如何在Playwright中编写校验元素文本转整数大于0的测试用例

Playwright数值校验实现方案

该需求完全可以在Playwright中实现,你原有代码的主要问题是page.$eval/page.$$eval的调用方式有误,缺少了获取元素文本的回调函数,修正后的实现代码如下:

test("searching for 0100t should show a out of pocket expense", async({ page })=>{
    // $eval第二个参数为回调函数,用于从匹配的元素中提取文本内容
    const surgicalCentersCostText = await page.$eval('.chart-inner-label-cost >> nth=0', el => el.textContent.trim())
    const hospitalOutpatientCostText = await page.$eval('.chart-inner-label-cost >> nth=1', el => el.textContent.trim())
    // 处理文本转数值,如需支持小数可将parseInt替换为parseFloat
    const surgicalCentersCost = parseInt(surgicalCentersCostText.replace('$',''))
    const hospitalOutpatientCost = parseInt(hospitalOutpatientCostText.replace('$',''))
    // 两个断言只要有一个不满足大于0的条件,就会触发测试失败
    expect(surgicalCentersCost).toBeGreaterThan(0)
    expect(hospitalOutpatientCost).toBeGreaterThan(0)
})

补充说明

  • 如果页面展示的数值存在千位分隔符(比如$1,200),可以修改替换逻辑为replace(/[$,]/g, '')避免转换失败
  • Playwright内置的expect断言支持全量数值判断方法,可根据需求替换为toBeGreaterThanOrEqual、toBeLessThan等其他方法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 14:06:09