Playwright Python. - How to check if an element is hidden

Viewed 2521

I'm currently using Playwright / Python / Pytest and I am attempting to user login as a particular type of user role and then check to see if various buttons are visible or hiddedn.

I am using page object and have set properties up for each button element i.e.

    @property
    def manage_placements_button(self):
    return self.page.wait_for_selector("xpath=//h3[normalize-space()='Manage Placements']")
    
    @property
    def my_holiday_button(self):
    return self.page.wait_for_selector("xpath=//h3[normalize-space()='My Holiday']")

    @property
    def my_payments_button(self):
    return self.page.wait_for_selector("xpath=//h3[normalize-space()='My Payments']")

    @property
    def my_compliances_button(self):
    return self.page.wait_for_selector("xpath=//h3[normalize-space()='My Compliances']")

Then I am using a verify method for the visible buttons:

    def verify_candidiate_can_see(self):
    result = self.manage_timesheets_button.is_visible()
    result = self.my_payments_button.is_visible() and result
    result = self.my_holiday_button.is_visible() and result
    result = self.my_compliances_button.is_visible() and result
    return result

This works fine and it passes back true for the assertion in the test.

I am then attempting to do the same with the hidden values using:

    def verify_candidiate_cant_see(self):
    result = self.manage_placements_button.is_hidden()
    return result

but I get this error - waiting for selector "xpath=//h3[normalize-space()='Manage Placements']" to be visible

Here is the test:

  @pytest.mark.order(2)
  def test_candidate_login(context, env):
  page = context.new_page()
  home_page = HomePage(page)
  login_page = LoginPage(page)
  login_page.navigate(env)
  login_page.login(env, "Candidate")
  result1 = home_page.verify_candidiate_can_see()
  assert result1 == True
  result2 = home_page.verify_candidiate_cant_see()
  assert result2 == True
  context.close()

I assumed as I added is_hidden it would be ok as the element does not exist on the page but it appears it's still waiting for it to be visible. Any help would be greatly appreciated

1 Answers

You could wait for the selector to be hidden:

return self.page.wait_for_selector("xpath=something", state="hidden")

Which will return when the element is not there and waits until it hides if its on the page.

See here for reference.

Related