I'm trying to write a reusable Protractor function that will determine if an option with specified text is present in a dropdown list. Here is the function I've created with some attempts at inspecting the options.
public expectDropdownListOptionPresence(dropdownListID: string, isPresent: boolean, optionText: string) {
// Determine if the desired option text is present or missing from the target list.
// Set isPresent to true when it should appear, and false when it shouldn't appear.
// Attempt 1
element.all(by.id(dropdownListID)).filter(function (lists) {
// Make sure the list is visible.
return lists.isDisplayed().then(function (isVisible) {
return isVisible;
}).then(function (visibleLists) {
// Nope, "Property 'all' does not exist on type 'Boolean'."
// visibleLists.all.getItem(by.css('option'))
})
});
// Attempt 2
element(by.id(dropdownListID)).$('option').filter(function (listOptions) {
// Nope, "Property 'filter' does not exist on type 'ElementFinder'."
});
}
You can see a couple of attempts, and I've included the warnings that WebStorm issues on some things that I've tried.
I've investigated this SO post on selecting an option. (How to select option in drop down protractorjs e2e tests) Unlike that post, my goal isn't to select the option, but just to inspect the dropdown list and determine if an option is present in the list, or if it is not present in the list.
=== Edit 12/16/2016 ===
Here is the code I adapted from the solution provided by @alecxe. I changed the function name to make it more readable. This works as desired. Thank you!
public expectDropdownListContains(dropdownListID: string, isPresent: boolean, optionText: string) {
// Determine if the desired option text is present or missing from the target list.
// Set isPresent to true when it should appear, and false when it shouldn't appear.
var foundOptions = element(by.id(dropdownListID)).$$('option').filter(function (option) {
return option.getText().then(function (text) {
return text === optionText;
});
});
if (isPresent === true) {
expect(foundOptions.count()).toBeGreaterThan(0);
} else {
expect(foundOptions.count()).toEqual(0);
}
}