Page Objects for Playwright Java made easy!
Stagehand is a Java library that helps you create clean and readable Page Objects. Inspired by Selenium's PageFactory, Stagehand allows you to create locators easily by annotating fields.
<dependency>
<groupId>io.github.uchagani</groupId>
<artifactId>stagehand</artifactId>
<version>2.1.0</version>
</dependency>
Creating a Page Object is as easy as annotating your class with @PageObject
:
@PageObject
public class HomePage {
}
To define Locators, create a Field and annotate it with @Find
:
@PageObject
public class HomePage {
@Find("#some-id")
private Locator myButton;
}
@Find
accepts any Playwright Selector.
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.
Stagehand gives you the ability to easily locate elements inside an Iframe by passing in a selector to find the Iframe:
@PageObject(frame = {".iframe-foo"})
public class PageWithIframe {
@Find("#iframe-button")
public Locator someButton;
}
Any Locators defined inside a class that is decorated with @PageObject(frame = {"X"}
will be scoped to that Iframe.
You can find nested Iframes by passing in multiple parameters to frame
.
The above example is equivalent to Playwright's page.frameLocator(".iframe-foo").locator("#iframe-button")
.
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 in Stagehand you can use the @Under
annotation:
@PageObject
public class HomePage {
@Find("#parent")
public Locator parentLocator;
@Under("parentLocator")
@Find(".child")
public Locator childLocator;
@Under("parentLocator")
@Find(".another-child")
public Locator anotherChild;
}
The value you pass to the @Under
annotation should be the name of the parent Locator.
Stagehand allows you to define a method that will automatically be called after creation of the page object by the
PageFactory.
To define a hook implement the AfterCreate
interface and put whatever code you want in that method.
import io.github.uchagani.stagehand.AfterCreate;
@PageObject
public class HomePage implements AfterCreate {
@Find("#some-id")
private Locator myButton;
@Override
public void afterCreate() {
myButton.click();
}
}
Stagehand makes it easy to define custom elements. See the code in src/test/java/io/github/uchagani/stagehand/custom
for an example on how to create custom elements.
See this test
on how to use custom elements in your tests.
Stagehand requires Java 8+ and Playwright 1.18.0+.