如何在 playwright 中编写此测试:if element text as int is > 0 test pass else test fail

Posted

技术标签:

【中文标题】如何在 playwright 中编写此测试:if element text as int is > 0 test pass else test fail【英文标题】:how to write this test in playwright: if element text as int is > 0 test pass else test fail 【发布时间】:2021-12-28 19:55:24 【问题描述】:

我正在尝试查看页面上显示的数字是否大于 0。 如果是我需要通过测试 如果不是,我需要测试失败

目前为止的代码

test("searching for 0100t should show a out of pocket expense", async()=>
    let surgicalCentersCost = await page.$$eval('.chart-inner-label-cost >> nth=0')
    let hospitalOutpatientCost = await page.$$eval('.chart-inner-label-cost >> nth=1')
    surgicalCentersCost = surgicalCentersCost.replace('$','');
    hospitalOutpatientCost = hospitalOutpatientCost.replace('$','');
    surgicalCentersCost = parseInt(surgicalCentersCost);
    hospitalOutpatientCost = parseInt(hospitalOutpatientCost)
    expect(surgicalCentersCost) // <-- what happens here?

  )

基本上我喜欢一个 if 语句,它查看 surgicalCentersCosthospitalOutpatientCost 并且如果两者都是 > 0 信号测试通过,否则信号测试失败

我知道我们可以在 cypress 中做这样的事情,但我工作的公司坚持要剧作家。这样的事情可能吗?

【问题讨论】:

.chart-inner-label-cost &gt;&gt; nth=0 解析为什么?您可能需要将代码替换为 let surgicalCentersCost = await page.locator('.chart-inner-label-cost &gt;&gt; nth=0').innerText() 之类的代码,如果没有看到页面就很难分辨。至于你需要的预期条件expect(surgicalCentersCost &gt; 0).toBeTruthy(); expect(hospitalOutpatientCost &gt; 0).toBeTruthy(); 【参考方案1】:

我即将对此进行测试,但看起来正则表达式是要走的路。观察最后两行。

test("searching for 0100t should show a out of pocket expense", async()=>
    let surgicalCentersCost = await page.$$eval('.chart-inner-label-cost >> nth=0')
    let hospitalOutpatientCost = await page.$$eval('.chart-inner-label-cost >> nth=1')
    surgicalCentersCost = surgicalCentersCost.replace('$','');
    hospitalOutpatientCost = hospitalOutpatientCost.replace('$','');
    surgicalCentersCost = surgicalCentersCost.replace(',','');
    hospitalOutpatientCost = hospitalOutpatientCost.replace(',','');
    surgicalCentersCost = parseInt(surgicalCentersCost);
    hospitalOutpatientCost = parseInt(hospitalOutpatientCost)
    await expect(surgicalCentersCost).toHaveValue(/^[1-9][0-9]*$/)
    await expect(hospitalOutpatientCost).toHaveValue(/^[1-9][0-9]*$/)

  )

【讨论】:

以上是关于如何在 playwright 中编写此测试:if element text as int is > 0 test pass else test fail的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Playwright 关闭弹出消息框?

playwright录制脚本

如何配置 playwright-jest 以排除测试套件(规范)文件以进行运行?

使用 Playwright 对 ASP.NET Core 应用执行功能测试

在 Playwright 中,如何通过命令行传递 baseUrl,以便我的规范文件没有我正在测试的应用程序的硬编码 url?

如何在 Playwright.js 中检查页面上是不是存在元素