Cic*_*518 12 javascript testing automated-tests typescript 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*
Run Code Online (Sandbox Code Playgroud)
有没有有效的方法来做这些事情?我在剧作家文档中没有找到任何内容。
the*_*ton 12
它可以在 JavaScript 中实现,类似于使用伪代码,如果指定的元素不在 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*
Run Code Online (Sandbox Code Playgroud)
有些人可能会注意到文档中的警告“不鼓励使用 ElementHandle,请改用Locator对象和 Web 优先断言”。默认情况下,您不必担心在 e2e 测试或抓取工具中使用 ElementHandles 或将它们与 Playwright 的定位器混合在一起,它们是从Puppeteer继承的,并且在 Playwright 中也能可靠地运行(如果不这样做:微软就会弃用它们)。Microsoft 之所以提倡定位器而不是元素句柄,只是因为他们在过去几年中投入的大部分额外功能(例如“getByAltText”、“getByLabel”等)都是构建在定位器之上的,因此您可以在他们的帮助下更轻松地编写 e2e 测试。这就是文档中发出警告的原因。您无需不惜一切代价避免使用元素句柄。
如果您想在条件语句中重用定位器,可以使用
locator.isVisible().
const myElement = page.locator('#elem-id')
if (await myElement.isVisible()) {
await myElement.click()
}
// code goes on with *next lines of code*
Run Code Online (Sandbox Code Playgroud)
小智 0
尽管剧作家建议使用定位器,但如果
if ((await page.$('#elem-id')) !== null) {
await page.click('#elem-id')
}
// code goes on with *next lines of code*
Run Code Online (Sandbox Code Playgroud)
工作顺利吗,这个解决方案可以使用吗?
| 归档时间: |
|
| 查看次数: |
23162 次 |
| 最近记录: |