Page Objects for Playwright Java made easy!
Is a Java library that helps you create clean and readable Page Objects. Inspired by Selenium's PageFactory, solution allows you to create locators easily by annotating fields.
<dependency>
<groupId>io.github.adv4nt4ge</groupId>
<artifactId>playwright-factory</artifactId>
<version>1.2.1</version>
</dependency>
To define Locators, create a Field and annotate it with @FindBy
:
public class HomePage {
@FindBy(locator = "#some-id")
public Locator header;
@FindBy(testId = "some-id")
public Locator myButton;
@FindBy(placeholder = "#some-id")
public Locator myPlaceholder;
@FindBy(altText = "#some-id")
public Locator myAltText;
@FindBy(text = "#some-id")
public Locator myText;
@FindBy(label = "#some-id")
public Locator myLabel;
@FindBy(title = "#some-id")
public Locator myTitle;
@FindBy(text = "#some-id")
public List<ElementHandle> myListText;
}
@FindBy(locator = "")
accepts any Playwright Other Locators.
To use your Page Object in your tests use the PageFactory
to create an instance of your page and pass it your page
class and an instance of Playwright's Page:
HomePage homePage=PageFactory.create(HomePage.class,page)
The PageFactory can create an instance of any page that has a default constructor or a constructor with just a Playwright Page parameter.
public void initElementsPageWithFieldDecorator() {
HomePage homePage = new HomePage();
PageFactory.initElements(homePage, new ElementFieldDecorator(page));
}
For an example of creating a test with Page Factory in your project
At times, you may want to find a locator that is under another locator. The way to do this in Playwright would
be: page.locator("#parent").locator(".child")
. To define this you can use the @Parent
annotation:
public class HomePage {
@FindBy(testId = "some-id")
public Locator parentLocator;
@Under("parentLocator")
@FindBy(locator = "#some-id")
public Locator childLocator;
@Parent("parentLocator")
@FindBy(placeholder = "#some-id")
public Locator anotherChild;
}
The value you pass to the @Parent
annotation should be the name of the parent Locator. The child Locator must be public.
The solution allows you to quickly locate elements inside an Iframe by passing in a selector to find the Iframe:
@Frame(frame = "#preview-iframe")
public class PageIframe {
@FindBy(testId = "some-id")
public Locator someButton;
}
Any Locators defined inside a class that is decorated with @Frame(frame = "X"
will be scoped to that Iframe.
The above example is equivalent to Playwright's page.frameLocator("#preview-iframe").getByTestId("some-id")
.
Solution requires Java 8+ and Playwright 1.30.0+.