首页 > 解决方案 > 如何在 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 文档中没有找到任何内容。

标签: javascripttypescripttestingautomated-testsplaywright

解决方案


它可以在 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*

推荐阅读