如何在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 afalsevalue instead of the test crashing—perfect for our if/else check. - Flexible Else Branch: Replace the placeholder
console.logwith 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
相关产品推荐
相关产品推荐

