Protractor中isEnabled()返回undefined问题求助
isEnabled() return undefined in Protractor? The core issue here is that all Protractor element interaction methods (including isEnabled()) are asynchronous and return Promises, not immediate boolean values. Your current synchronous code isn't waiting for the Promise to resolve, so when you check us_dat.isEnabled() == false, you're actually comparing a pending Promise object to false—which evaluates to false, and in debugging, this might appear as undefined because the Promise hasn't completed yet.
Here's what's happening in your code:
- When
dat > 24, you initializeus_datto the first matching element. - You call
us_dat.isEnabled()which returns a Promise, not a boolean. - Comparing this Promise to
falsegivesfalse, so your code skips theifblock where you'd switch to the second element. - You then try to click the first element, which might be disabled, leading to unexpected behavior.
Fixed Code Using Async/Await
Protractor fully supports async/await (introduced in version 5), which makes handling asynchronous operations much cleaner. Here's your refactored code:
async function selectCalendarDate(dat) { // Start with the first matching date element let targetDateElement = element(by.xpath(`(//a[text()='${dat}'])[1]`)); // For dates >24, check if the first element is enabled if (dat > 24) { const isElementEnabled = await targetDateElement.isEnabled(); // Switch to the second element if the first is disabled if (!isElementEnabled) { targetDateElement = element(by.xpath(`(//a[text()='${dat}'])[2]`)); } } // Wait for the click to complete and add a sleep (note: prefer explicit waits over sleep when possible) await targetDateElement.click(); await browser.sleep(1000); }
Key Changes Explained:
- Wrapped the logic in an
asyncfunction: This allows us to useawaitto pause execution until each Promise resolves. - Used
awaitwithisEnabled(): This waits for the Promise to resolve and gives us the actual boolean value (trueorfalse) for our condition check. - Added
awaittobrowser.sleep(): Evensleep()returns a Promise, so we need to wait for it to complete too. - Simplified initial element selection: Since both branches of your original
if/elsestarted with the same element, we can initialize it once and only adjust it when needed.
Bonus Tip:
Avoid using browser.sleep() for waits whenever possible—instead, use Protractor's explicit waits (like browser.wait()) to wait for specific conditions (e.g., element to be clickable). This makes your tests more reliable and faster. For example:
const EC = protractor.ExpectedConditions; await browser.wait(EC.elementToBeClickable(targetDateElement), 5000); await targetDateElement.click();
内容的提问来源于stack exchange,提问作者Sayanthan

