Assertions in a Page Object, god objects and inheritance
A Page Object has one reason to change: the page changed, so business assertions with hard-coded values, god objects and deep inheritance hurt it. Assertions stay in the test, with a page-state wait such as expectLoaded allowed; shared parts move into components through composition and preconditions into fixtures. A method returning a boolean through isVisible gives a snapshot without waiting, so a locator is returned instead.
Patterns · Page Object
A Page Object has verifyTotalIs100() and the test does not show what it checks. Where is the line?
A Page Object started with two methods and a year later it is a file of 1500 lines. It has verifyTotalIs100(), three different ways to log out, a waitForTimeout after every click and a base class that three more inherit from. The test "add items and check the total" reads as five method calls, and what it actually checks is not visible. This lesson takes apart three typical failures: assertions inside, a god object and inheritance chains, shows the fix and names the trade-offs honestly.
How it works and why. A Page Object has one reason to change: the page changed. Every extra responsibility adds another reason. An assertion in the class means the class changes when the requirement for the result changes. Creating data means a change when the API changed. A base class with utilities for everyone means the class changes when anything in the project changes. All three failures share a root: the class stops describing a page and becomes a warehouse for everything. So the cure is not "prettier code" but a return to one responsibility.
Assertions. There are two positions. Fowler advises keeping checks in tests: the class shows how the page is built and the test decides what counts as correct. An acceptable compromise: a method that waits for the page's own state (expectLoaded() checks that the heading is visible), because that is synchronisation, not a business check. A method verifyTotalIs100() is worse: the number 100 is hidden from the test, the method works for one value only, and on failure the report shows a class, not a scenario.
Where the total check lives
verifyTotalIs100() in the Page Object
The goal of the test is hidden and the number is baked into the method. A total of 250 needs another method.
expect(orders.total) in the test
The number and the condition are visible in the scenario. The class gives only the total locator, one for all tests.
Inheritance. A chain BasePage → AuthenticatedPage → AdminPage → AdminUsersPage looks tidy until the base class has to change. Then everything below is affected, and to understand where a method comes from the reader walks through four files.
An inheritance chain
Example: from a god object to two classes. The initial class. Four problem places are marked.
export class OrdersPage {
constructor(private page: Page) {}
1 async verifyTotalIs100() {
await expect(this.page.locator('.total')).toHaveText('100');
}
async addItem(name: string) {
await this.page.locator('.search').fill(name);
await this.page.locator('.add-btn').click();
2 await this.page.waitForTimeout(2000);
}
async logout() {
3 await this.page.locator('.avatar').click();
await this.page.locator('text=Logout').click();
}
4 async isCartEmpty() {
return this.page.locator('.cart-empty').isVisible();
}
// …40 more methods: filters, admin tables, checkout
}
- An assertion in the class: the number is baked into the name and the goal of the test is hidden.
waitForTimeout(2000)instead of auto-waiting: slow, and still unstable on a slow machine.- The user menu lives in OrdersPage. The same
.avatargets copied into every class and drifts apart. isVisible()does not wait: it answers at once, and a test that checks it withtoBe(true)is unstable.
The diagnosis from the symptoms: the class collects whatever the tests wanted, so it mixes the orders page, the header, synchronisation and checks. The cure has three steps: move the header into a component, remove the waits and the assertions, give the locators to the test.
export class Header {
readonly menu: Locator;
readonly logoutItem: Locator;
constructor(page: Page) {
this.menu = page.getByRole('button', { name: 'Account' });
this.logoutItem = page.getByRole('menuitem', { name: 'Log out' });
}
async logout() {
await this.menu.click();
await this.logoutItem.click();
}
}
The header is now one for the whole project, and every Page Object plugs it in by composition: this.header = new Header(page). Instead of a BasePage with everything, a class has only the parts it needs.
export class OrdersPage {
readonly header: Header;
1 readonly total: Locator;
readonly emptyCart: Locator;
constructor(private readonly page: Page) {
2 this.header = new Header(page);
this.total = page.getByTestId('order-total');
this.emptyCart = page.getByText('Your cart is empty');
}
3 async addItem(name: string) {
await this.page.getByRole('searchbox').fill(name);
await this.page.getByRole('button', { name: 'Add' }).click();
}
}
- The locator is public: the test checks the total itself.
- The header is plugged in by composition, not inheritance.
- An action without sleep: Playwright waits for the search field and the button itself.
The test now shows everything important:
test('total after two items', async ({ page }) => {
const orders = new OrdersPage(page);
await page.goto('/orders');
await orders.addItem('Keyboard');
await orders.addItem('Mouse');
await expect(orders.total).toHaveText('100');
await expect(orders.emptyCart).toBeHidden();
await orders.header.logout();
});
The number 100 and the conditions are visible in the scenario. Instead of isCartEmpty() with a boolean, the test uses expect(orders.emptyCart).toBeHidden(), which retries until the condition holds. If the same check repeats in dozens of tests, a method expectTotal(value) is acceptable too: the number comes from the test.
Limits and alternatives. None of the rules is absolute. Some teams deliberately put assertions in the Page Object, and for two or three repeated checks with parameters it works, especially when everyone understands the convention. The problem starts when names turn into verifyXIsY. A base class is sometimes justified too, if it is tiny: two or three things that every page really needs. But as soon as a second level appears, it is time to move to composition. For complex screens with repeated blocks there are components, for shared setup (login, data) Playwright fixtures, and for scenarios with different roles Screenplay, which swaps pages for tasks. Each option adds its own layer, so pick the one that solves a real problem of your suite.
Common mistakes.
- Methods like
verifyTotalIs100: the test does not show its goal and the class grows with every new value. - A class of a thousand lines "about everything": constant merge conflicts, duplicate methods, nobody knows what already exists. Split by screens and components.
waitForTimeoutinside methods: it masks instability and slows everything. Rely on auto-waiting and web-first assertions.- A method that returns a
booleanfromisVisible(): that is a snapshot without waiting. Return the locator and check it throughexpect. - A Page Object creates data or calls the API: that is another responsibility. Preconditions belong to fixtures and App Actions.
Check yourself
A test has expect(await orders.isCartEmpty()).toBe(true) and sometimes fails on a slow environment. What happens and how to fix it?
Answer
isVisible() does not wait: it returns the state at the moment of the call, so while the cart is still emptying we get false and the test fails. The fix: return the locator and check it with a web-first assertion, await expect(orders.emptyCart).toBeVisible(), which retries the search until the timeout.
BasePage has waitForSpinner() that 30 pages inherit. A new page has no spinner. How to restructure without breaking the rest?
Answer
Move the spinner into a Spinner component (or a fixture) and plug it in by composition only for pages that need it. BasePage then loses the method and the new page does not inherit anything extra. This is “composition instead of inheritance”.