Protractor调用外部自定义定位器报错,寻求解决方案
Let's walk through fixing the issues with your custom button locator. I spotted a few key problems in your code that are causing the error:
1. Syntax & Export Issues in Custom Locator File
Your buttontextcusloc.js has unclosed curly braces and an incorrect export approach. Here's the corrected version:
// customlocators/buttontextcusloc.js by.addLocator('buttonTextSimple', function(buttonText, opt_parentElement, opt_rootSelector) { // Use parent element if provided, else document var using = opt_parentElement || document; var buttons = using.querySelectorAll('button'); // Trim text to handle accidental spaces/newlines in button content return Array.prototype.filter.call(buttons, function(button) { return button.textContent.trim() === buttonText.trim(); }); }); // We don't need to export a constructor here — just running addLocator registers the locator globally module.exports = {};
The main fixes here:
- Closed all missing curly braces in the
addLocatorcallback - Removed the unnecessary
new buttontxtcustomlocator()export (since we're just registering a locator, not creating an instance) - Added
trim()to both the button text and input text to make matching more reliable (buttons often have hidden whitespace in their HTML)
2. Correct Path in Config.js
When requiring your custom locator, make sure you use a relative path from your config file to the customlocators folder. If config.js is in your project root, update the require statement like this:
// config.js // Add ./ to reference the current directory require('./customlocators/buttontextcusloc.js'); exports.config = { directConnect: true, framework: 'jasmine', // Don't forget to include your spec file path specs: ['com/sam/scripts/customloctestcase.spec.js'], // Other config options... };
Without ./, Node.js will look for customlocators in the global node_modules folder instead of your project directory.
3. Optional: Add Wait for Element Presence
To avoid "element not found" errors due to page loading delays, add a wait using Protractor's ExpectedConditions:
// com/sam/scripts/customloctestcase.spec.js var EC = protractor.ExpectedConditions; describe('Custom Locator Script', function() { it("check custom locator", function() { browser.get("http://www.way2automation.com/angularjs-protractor/registeration/#/login"); // Wait up to 5 seconds for the button to appear var goButton = element(by.buttonTextSimple('Go!')); browser.wait(EC.presenceOf(goButton), 5000); goButton.click(); }); });
4. Verify Execution
Run your Protractor command again (double-check your config filename matches what you're referencing):
protractor defaultconfig.js
内容的提问来源于stack exchange,提问作者Sameera De Silva

