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

如何在Protractor中使用JavaScript的if/else条件?含元素等待场景

How to Add If/Else Conditional Logic for Element Presence in Protractor

Got it, let's tweak your code to include the conditional check you need. The core trick here is using Protractor's browser.wait() method, which returns a promise that resolves to true if the condition is met within the timeout, and false if it times out. We'll use async/await to keep the logic clean and easy to follow.

First, just a quick reminder to make sure you've imported ExpectedConditions (you're already using EC in your code, so this is just confirming):

const EC = protractor.ExpectedConditions;

Here's the revised selectPing() method with the if/else logic:

async selectPing() {
  // Click the initial Ping button
  await element(by.xpath('//button[text()= "Ping"]')).click();
  
  // Optional fixed sleep (note: explicit waits are more reliable than fixed sleeps when possible)
  await browser.driver.sleep(5000);
  
  // Define the target Ok button element
  const pingStatus = element(by.buttonText('Ok'));
  
  // Wait for the button to be clickable, catch timeouts to return false instead of throwing an error
  const isOkButtonAvailable = await browser.wait(EC.elementToBeClickable(pingStatus), 25000).catch(() => false);
  
  if (isOkButtonAvailable) {
    // If the button is found and clickable, proceed to click it
    await pingStatus.click();
    console.log('Successfully interacted with the Ok button');
  } else {
    // Handle the scenario where the Ok button wasn't found/clickable within the timeout
    console.log('Ok button not accessible within the specified wait time');
    // Add your custom else-branch logic here (e.g., take a screenshot, log detailed error, run alternative steps)
  }
}

Quick Breakdown of Key Changes:

  • Async/Await: This lets us handle Protractor's promise-based API in a synchronous-looking way, making the conditional flow easier to read.
  • Error Handling for Wait: The .catch(() => false) ensures that if the wait times out (or hits any other error), we get a false value instead of the test crashing—perfect for our if/else check.
  • Flexible Else Branch: Replace the placeholder console.log with whatever logic you need for the failure case (like capturing a screenshot, marking the test as failed, or executing fallback steps).

内容的提问来源于stack exchange,提问作者Rahul Solanki

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:49:35