使用Protractor测试时如何定位ng-content的最后一个元素
Got it, let's figure out how to locate and click the last element inside ng-content using Protractor. Here are a few practical approaches tailored to different scenarios:
1. Use CSS Selectors to Target the Last Child
When ng-content renders, its content becomes direct child elements of the host component. You can leverage CSS pseudo-classes to grab the final one directly:
- If you just need the very last direct child (regardless of element type):
// Replace 'your-host-component' with the actual selector of your component element(by.css('your-host-component > :last-child')).click(); - If you need to target the last element of a specific type (e.g., the last
<button>or<div>):element(by.css('your-host-component > button:last-of-type')).click();
2. Fetch All Child Elements and Pick the Last One
This approach is great if you need to perform additional checks (like verifying the number of elements) before clicking:
// First locate the parent container holding the ng-content const contentContainer = element(by.tagName('your-host-component')); // Get all direct child elements and click the last one contentContainer.all(by.css('> *')).last().click();
You can also narrow down the elements by class or tag if needed—just adjust the by.css() selector inside all().
3. Combine with Angular-Specific Locators (If Applicable)
If the elements inside ng-content are Angular components or have unique Angular attributes, you can use Protractor's Angular-aware locators:
- For a specific component type:
element.all(by.tagName('app-custom-button')).last().click(); - For elements with a specific class:
element.all(by.css('.content-item')).last().click();
Pro Tip: Ensure the Element is Ready to Click
Sometimes you might run into timing issues. Add an explicit wait to make sure the element is clickable before interacting with it:
const EC = protractor.ExpectedConditions; const targetElement = element(by.css('your-host-component > :last-child')); // Wait up to 5 seconds for the element to be clickable browser.wait(EC.elementToBeClickable(targetElement), 5000); targetElement.click();
Just a quick reminder: Always double-check the rendered DOM with your browser's dev tools first—sometimes ng-content might be wrapped in extra containers, so you'll need to adjust your parent selector accordingly.
内容的提问来源于stack exchange,提问作者Unmesh Ghatbandhe

