Home > OS >  Looping through IWebElements elements and comparing with IList string
Looping through IWebElements elements and comparing with IList string

Time:02-08

My DOM elements:

<ul id="testList"  xpath="1">
  <li >Carp and its Derivatives</li>
  <li >Tilapia and its Derivatives</li></ul>

What I'm trying to achieve is to:

a) Get main element (testList) or get main element element's (li)

private readonly string allergensDoesContainListLocator = "//ul[@id = 'testList']//li";
public IList<IWebElement> AllergensDoesContainList => driver.FindElements(By.XPath(allergensDoesContainListLocator));

b) Create list of element which I want to pass & assert:

IList<string> DoesContainAllergens => new List<string>(new string[] { "Carp and its Derivatives", "Tilapia and its Derivatives" });

c) Write proper loop method I was thinking about simple LINQ something like:

AllergensDoesContainList.Where(c => c.Text == allergensToCheck)

Or ForEach statement

          //allergensToCheck.ForEach(delegate (string name)
                  //{
                  //    bool isAllergenVisible = driver.IsElementVisible(By.XPath(string.Format("//div[@data-automation='sizePanel[{0}]'][contains(.,'{1}')]", sizeIndex, name)));
                  //});

Can someone advice me what will be the perfect way? Using NUnit for a unit test provider, if that helps.

CodePudding user response:

This involves two main steps. First, collect all of the text into an IEnumerable<string>. Next, use the CollectionAssert class in NUnit to make your assertion:

private readonly string allergensDoesContainListLocator = "//ul[@id = 'testList']//li";
private IList<IWebElement> AllergensDoesContainElements => driver.FindElements(By.XPath(allergensDoesContainListLocator));

private IEnumerable<string> AllergensDoesContainList => AllergensDoesContainElements.Select(element => element.Text);

Now you can make your assertion:

var expectedAllergens = new string[]
{
    "Carp and its Derivatives",
    "Tilapia and its Derivatives"
};

// If the order on screen matters to your assertion:
CollectionAssert.AreEqual(expectedAllergens, AllergensDoesContainList);

// If the order on screen does not matter:
CollectionAssert.AreEquivalent(expectedAllergens, AllergensDoesContainList);
  •  Tags:  
  • Related