javascript - 如何在 PLAYWRIGHT 上使用选择器制作条件语句?
问题描述
我需要一些帮助来使用 Playwright 测试制作条件语句。
我有一个给定的选择器,比如说一个按钮,我需要写一个这样的条件语句:
if (selector is not present/visible)
do nothing and proceed with the *next lines of code*
else
await page.click(*selector*)
*next lines of code*
有没有有效的方法来做这些事情?我在 Playwright 文档中没有找到任何内容。
解决方案
它可以在 JavaScript 中实现,类似于您的伪代码 using ,如果指定的元素不在 DOM 中page.$(selector)
,则返回。null
(注意:注意条件中括号的正确用法!)
我还将您的初始if(falsy)...else
条件反转为单个if(truthy)
,因为您只想在选择器存在时执行命令,否则 else 分支没有太大意义:
if ((await page.$('#elem-id')) !== null) {
await page.click('#elem-id')
}
// code goes on with *next lines of code*
推荐阅读
- flutter - Flutter ListView 对 StatefulWidget 项的状态匹配错误
- powershell - 从 web api 为多个请求调用 powershell 命令
- javascript - 使用 jQuery 对单选按钮状态的反应
- python - Python typehint 从类型元组作为参数的联合返回类型
- javascript - 即使可能的输出数量(arr.length)增加,如何将输入(int 0-99)映射到相同的输出(arr [n])
- r - Sankey NetworkD3:在整个流程中设置链接颜色
- javascript - 更新 XCode、NativeScript-socketio 后出错?
- java - 在数组中输入浮点类型
- vue.js - f7route 不是函数 Vue 3 框架7
- matplotlib - 在 Seaborn catplot 中更改轴标签大小