Search code examples
c#.netnunitplaywrightplaywright-dotnet

Playwright .NET NUnit: Locating nested checkbox within divs


In my PlayWright application (.NET within NUnit). I am trying to tick the 'Yes' box of Question 2 below

Picture of Questions

Here's my code:

await page
    .Locator("div").Filter(new() { HasText = "Question 2 (Help find me and tick yes)" })
    .Locator("label").Filter(new() { HasText = "Yes" })
    .Locator("span").ClickAsync();

The aim for me is that it will filter out all other 'divs' and only return the div with question 2 thanks to the filter on "Question 2 (Help find me and tick yes)"

I'm getting the below error message in that it doesn't seem to be correctly filtering out the first Question.

Microsoft.Playwright.PlaywrightException : Error: strict mode violation: Locator("div").Filter(new() { HasText = "Question 2 (Help find me and tick yes)" }).Locator("label").Filter(new() { HasText = "Yes" }).Locator("span") resolved to 2 elements:

html (angular):

<app-custom-angular-app1>
   <div>
      <label>Question 1</label>
      <app-yes-no>
         <fieldset>
            <div><label>Yes<input type="radio" required=""><span class="radioButton"></span></label></div>
            <div><label>No<input type="radio" required=""><span class="radioButton"></span></label></div>
         </fieldset>
      </app-yes-no>
   </div>
</app-custom-angular-app1>
<app-custom-angular-app2>
   <div>
      <label>Question 2 (Help find me and tick yes)</label>
      <app-yes-no>
         <fieldset>
            <div><label>Yes<input type="radio" required=""><span class="radioButton"></span></label></div>
            <div><label>No<input type="radio"required=""><span class="radioButton"></span></label></div>
          </fieldset>
      </app-yes-no>
   </div>
</app-custom-angular-app2>

Solution

  • This should make it unique by adding fieldset:

    await page
        .Locator("fieldset div").Filter(new() { HasText = "Question 2 (Help find me and tick yes)" })
        .Locator("label").Filter(new() { HasText = "Yes" })
        .Locator("span").ClickAsync();
    

    Note: The problem with HasText is , it matches any element containing specified text somewhere inside, also in a child or even in a descendant element somewhere down in the tree.

    So as its very broad in scope , narrow it down by ensuring uniqueness.