abstract, implements and inheritance in a Page Object
An abstract class cannot be created with new and forces subclasses to implement its abstract members. The implements keyword only checks conformance to an interface and inherits nothing. A base class constructor runs before the subclass fields are initialised, so it must not read them. In a Page Object keep at most one level of base class and compose the page from components passed in through fixtures.
TypeScript · Classes
A base class reads a path that a subclass sets and gets undefined. Why, and why use inheritance in a Page Object at all?
In a Page Object it is handy to move shared behaviour to a base class: open the page, wait for it to load. Subclasses set only their own path. All is well until the hierarchy grows: BasePage, then AuthorizedPage, then DashboardPage, then AdminDashboardPage, and a change at the second level breaks everyone. This lesson covers abstract, implements, initialisation order, and where inheritance works in a framework and where composition is better.
How it works and why. An abstract class cannot be created with new: it holds shared logic and declares abstract members without a body that every descendant must implement. The compiler will not let a descendant exist unless it implements all abstract members. The keyword implements does something else: it checks that a class conforms to an interface but inherits nothing and generates nothing. The interface disappears after compilation, and structural typing already lets any object of the right shape be substituted, so implements is useful only as an early message about a mismatch inside the class itself.
export abstract class BasePage {
protected abstract readonly path: string;
constructor(protected readonly page: Page) {}
async open(): Promise<void> {
await this.page.goto(this.path);
await this.waitForLoaded();
}
protected abstract waitForLoaded(): Promise<void>;
}
export class AccountsPage extends BasePage {
protected readonly path = '/accounts';
protected async waitForLoaded(): Promise<void> {
await expect(
this.page.getByRole('heading', { name: 'Accounts' }),
).toBeVisible();
}
}
The open() method in the base class runs the shared scenario, and a descendant supplies the specifics through path and waitForLoaded(). This is the classic template method. The override keyword together with the noImplicitOverride option (TS 4.3) forces overrides to be marked explicitly, and renaming a method in the base class breaks the build instead of quietly producing a new method.
Initialisation order: a trap. In JavaScript the base class constructor runs before the subclass fields are initialised. If the base constructor reads this.path directly or indirectly, the field is still empty. TypeScript forbids direct access to an abstract property in a constructor but does not see it through a helper method.
abstract class BasePage {
protected abstract readonly path: string;
constructor(protected readonly page: Page) {
this.logOpen();
}
private logOpen() {
console.log('open ' + this.path); // open undefined
}
}
class AccountsPage extends BasePage {
protected readonly path = '/accounts';
}
new AccountsPage(page);
When subclass fields are assigned
The rule: do not read in a base constructor what a subclass sets. Do the work in a method called later (like open() above).
Example: a hierarchy that grows. A chain of four classes sounds logical:
class BasePage {}
class AuthorizedPage extends BasePage {}
class DashboardPage extends AuthorizedPage {}
class AdminDashboardPage extends DashboardPage {}
The problem is that each level adds implicit dependencies: AdminDashboardPage inherits a login method it does not need, and a change in AuthorizedPage touches every class below. A new trait ("a page with a header") can only be added as one more level, because there is no multiple inheritance.
The fix: assemble a page from components and hand it to tests through a Playwright fixture (that is how the documentation hands a Page Object to tests).
export class Header {
constructor(private readonly page: Page) {}
async logout() {
await this.page.getByRole('button', { name: 'Log out' }).click();
}
}
export class DashboardPage {
readonly header: Header;
constructor(private readonly page: Page) {
this.header = new Header(page);
}
}
export const test = base.extend<{ dashboard: DashboardPage }>({
dashboard: async ({ page }, use) => {
await use(new DashboardPage(page));
},
});
Now the header is a separate class that can be attached to any page, and the dependencies are visible in the constructor. A shared base class stays when it is truly single and thin.
Hierarchy or composition
Three or four inheritance levels
A change at a middle level touches everyone. New traits have to be built in as a new level.
Components and fixtures
A page is made of Header, Table, Form. Dependencies are visible, shared things travel through fixtures.
implements for interchangeable implementations. A useful case: two classes with one contract, a real one and a stub.
interface PaymentsGateway {
pay(amount: number, currency: string): Promise<{ txId: string }>;
}
class PaymentsApi implements PaymentsGateway {
async pay(amount: number, currency: string) {
const res = await api.post('/payments', { data: { amount, currency } });
return { txId: (await res.json()).txId as string };
}
}
class PaymentsStub implements PaymentsGateway {
async pay() {
return { txId: 'stub-1' };
}
}
A test takes PaymentsGateway and does not know which implementation is under it. If a method is added to the interface, both classes stop building.
Limits and alternatives.
- One level of base class is fine, three is a signal to refactor.
staticmembers belong to the class, not an instance. For constants and factories they fit. Static state is shared between tests of one worker (each Playwright worker is a separate process with its own module), and a test that changes it affects the next tests of that worker, hence flakiness.- A base can be not a class but a set of helper functions or a mixin if only shared behaviour is needed.
- Library classes such as Playwright's
Pageare usually not extended but wrapped in a class of your own.
Common mistakes.
- Reading in a base class constructor a property that the subclass sets: you get
undefined. - Building deep Page Object hierarchies: a change at the top breaks everything below.
- Treating
implementsas inheritance: code from an interface does not enter the class. - Keeping test state in
static: it lives as long as the worker.
Check yourself
In BasePage the constructor calls this.logOpen(), which prints this.path, and AccountsPage sets path = '/accounts'. The console shows undefined. Why?
Answer
The base class constructor runs before the subclass fields are initialised, so path is not assigned yet. Work that depends on subclass fields is done later in a method, not in the base constructor.
How does implements differ from extends, and what happens if a method is added to the interface?
Answer
extends inherits code, implements only checks conformity with an interface and adds nothing. If a method is added to the interface, every class with implements that lacks it stops building.
implements only checks a contract. Middle/Senior: In a Page Object I keep at most one level of base class and prefer composition from components passed through fixtures. I remember the initialisation order: the base constructor runs before the subclass fields, so I do not read subclass fields in it.