使用Protractor定位非Angular页面username元素的报错问题排查
Hey there, let's break down why you're running into that frustrating element-not-found error. Even though you've disabled Angular wait with browser.waitForAngularEnabled(false);, the problem is likely that Protractor is trying to click the "Logg inn" button before the element has finished loading or rendering on the page. Non-Angular pages don't have the Angular hooks Protractor relies on to detect when the page is ready, so we need to explicitly tell it to wait for the element to become available.
Here's how to fix your script:
We'll use Protractor's built-in ExpectedConditions to wait until the button is clickable—this is the most reliable way to handle timing issues in non-Angular pages.
describe('slowchat', function() { it('start test', function() { // Disable Angular wait for the non-Angular login page browser.waitForAngularEnabled(false); // Navigate to the login page browser.get('https://www.test.no/eai/bankid20'); // Define the login button element const loginButton = element(by.css('[value="Logg inn"]')); // Wait up to 10 seconds for the button to be clickable const EC = protractor.ExpectedConditions; browser.wait(EC.elementToBeClickable(loginButton), 10000, 'Login button did not become clickable within 10 seconds'); // Now safely click the button loginButton.click(); // Re-enable Angular wait for subsequent Angular pages browser.waitForAngularEnabled(true); }); });
Key improvements explained:
- Explicit wait: The
browser.wait()call ensures Protractor doesn't attempt to click until the button is both present in the DOM and interactable (not hidden or disabled). - Custom timeout message: Adding a descriptive message makes debugging easier if the element still fails to load.
- Reusable element reference: Storing the element in a variable avoids re-querying the DOM unnecessarily and keeps the code cleaner.
Quick troubleshooting if it still fails:
- Verify your CSS selector: Open the login page in your browser's dev tools console and run
document.querySelector('[value="Logg inn"]'). If this returnsnull, your selector is incorrect—double-check the element's attributes. - Adjust the wait condition: If the button loads dynamically (e.g., after an API call), try using
EC.presenceOf(loginButton)first to wait for it to exist in the DOM, then wait for it to be clickable. - Increase the timeout: If your test environment is slow, bump the
10000(10 seconds) value to a higher number like15000.
内容的提问来源于stack exchange,提问作者Magnus Jensen

