Using Python Playwright and Page Object Model
Scenario: Clicking a link opens a new tab. Rest of the oprations needs to be performed in new page.
Without Page Object model: I was able to accomplish this. Code below:
def run(playwright:Playwright) -> None:
browser = playwright.chromium.launch()
context = browser.new_context()
page= context.new_page()
page.goto(URL)
with context.expect_page as Account_setup_page:
accountSetup_link.click()
new_page = Account_setup_page.value
startaccount = new_page.locator('<<Xpath>>')
Above code is working fine, since the browser context is in the same code file.
Now, using page object model: Need some direction on how should we switchto new tab?
conftest.py file has the context reference:
@pytest.fixture(scope="function")
def accsetup(request,playwright)
browser=playwright.chromium.launch()
context=browser.new_context()
page=context.new_page()
page.goto(URL)
yield page
context.close()
browser.close()
Now, in the page code file:
filename: AccountSetupE2E.py
class AccountSetup:
def __init__(self,page)
self.page = page
self.username = page.locator(<<Xpath>>)
self.pwd = page.locator(<<Xpath>>)
self.login = page.locator(<<Xpath>>)
def fillaccountdetails(self):
self.username.fill("test")
self.pwd.fill("testpwd")
self.login.click()
Once login is successful, clicking on accountSetup_link will open new tab. I am unable to figure out a way to reference the new tab to perform accountsetup operations.
Application URL is opening..but unable to click even on username. It worked, when context was not returned. Only for this scenario, I need to use new tab to validate the test case.
I tried below and its not working:
contest.py:
@pytest.fixture(scope="function")
def accsetup(request,playwright)
browser=playwright.chromium.launch()
context=browser.new_context()
page=context.new_page()
page.goto(URL)
yield page,context
context.close()
browser.close()
filename: AccountSetupE2E.py
class AccountSetup:
def __init__(self,page,context)
self.page = page
self.context=context
self.username = page.locator(<<Xpath>>)
self.pwd = page.locator(<<Xpath>>)
self.login = page.locator(<<Xpath>>)
self.accountSetup_link =page.locator(<<xpath>>)
with context.expect_page() as Account_setup_page:
self.accountSetup_link.click()
new_page = Account_setup_page.value
self.startaccount = new_page.locator('<<Xpath>>')
def fillaccountdetails(self):
self.username.fill("test")
self.pwd.fill("testpwd")
self.login.click()
self.startaccount .click()
TestCasefile -> Test_Accountsetup.py
class Test_accsetup:
def test_accSetup(self,accsetup):
page,context=acc_setup
acpage = acc_setup(page,context)
acpage.fillaccountdetails()
context.pages. That should be a list containing the tabs. Your page objects could have an url or something which may be used to test against if the tab matches the page object. Or you can just index the tabs and map your page objects that way if your project is simple enough.