0

New to playwright, creating some sample stuff to find out how to use the tool.

enter image description here

From the image above, the getByRole works fine (while I recorded in playwright) but to get the xpath for this element it becomes like button/div and then using contains.

Question: How to use this getByRole directly in the page object model.

Currently I'm using like this:

private String txtEmail = "input[id=\"signinEmail\"]";
private String txtPwd = "input[id=\"signinPassword\"]";
private String btnLogin = "//button/div[contains(.,\"Log In\")]";
swame_sp
  • 59
  • 2
  • 10

1 Answers1

0

I'd highly recommend you stop using private fields to access elements on the page. All these eventually end up doing is creating busy work as you attempt to map out all the fields on the page and you end up referencing them a single time anyway. On the same note, you should ideally not use XPath or CSS to locate elements on the page, unless they are a last resort. Stick to using the Playwright Locators, such as getByRole, getByText, getByPlaceholder, etc, as in theory they should make your tests more robust.

That all being said, if you do want to keep mapping out the elements individually, you could do this...

private final Locator logInButton = page.getByRole(BUTTON, new Page.GetByRoleOptions().setExact(true).setName("Log In"));

Then when you want to use this button...

public void clickLoginButton() {
  logInButton.click();
}

And if you really wanted to make me cry, you could still use your XPath and do something like this...

private final String logInButton = "//button/div[contains(.,\"Log In\")]";

public void clickLoginButton() {
  page.locator("xpath=" + logInButton).click();
}
Iainn
  • 66
  • 6