javaplaywrightplaywright-java

Strict mode violation Error happens when I try select an option which is a substring of another option


First off, I want to tell you that I am new to this playwright tool. My problem is, I have two option male and female when I try to click male option in the list using the following code,

page.getByRole(AriaRole.LISTITEM).filter(new Locator.FilterOptions().setHasText("Male")).click();

it throws the following error

Exception in thread "main" com.microsoft.playwright.PlaywrightException: Error {
  message='Error: strict mode violation: getByRole(AriaRole.LISTITEM).filter(new Locator.FilterOptions().setHasText("Male")) resolved to 2 elements:
    1) <li id="cP1Q100" class="z-comboitem">…</li> aka getByRole(AriaRole.LISTITEM).filter(new Locator.FilterOptions().setHasText("Female"))
    2) <li id="cP1Q200" class="z-comboitem z-comboitem-sele…>…</li> aka getByRole(AriaRole.LISTITEM).filter(new Locator.FilterOptions().setHasText("Male"))

This happens because male is the substring of female. If I try to click the female option it happens without having any problem because female is unique here. How can I resolve this problem? I am using Java Playwright.


Solution

  • You may wanna try to use RegEx. And Pattern in Java, I believe it's case sensitive by default, while text is not.

    page.getByRole(AriaRole.LISTITEM)
      .filter(new Locator.FilterOptions().setHasText(Pattern.compile("Male"))).click();
    
    

    https://playwright.dev/java/docs/locators#filtering-locators