Returning Page Objects for Chaining
You'll learn how to make Page Object methods return other Page Objects, enabling fluent test flows that read like natural user journeys.
The Problem with Void Methods
Right now, your Page Object methods probably return nothing (void). This means every action requires a new statement:
const loginPage = new LoginPage(page);
loginPage.enterEmail('user@test.com');
loginPage.enterPassword('secret');
loginPage.clickSubmit();
const dashboardPage = new DashboardPage(page);
dashboardPage.waitForWelcome();
It works, but it's verbose and doesn't reflect the flowing nature of user interactions.
Return the Next Page Object
When a user action navigates to a new page (or stays on the same page), return the appropriate Page Object:
class LoginPage {
async login(email, password) {
await this.page.fill('#email', email);
await this.page.fill('#password', password);
await this.page.click('button[type="submit"]');
return new DashboardPage(this.page); // Returns next page
}
}
class DashboardPage {
async openSettings() {
await this.page.click('a[href="/settings"]');
return new SettingsPage(this.page); // Returns next page
}
}
Now your test flows chain naturally:
await new LoginPage(page)
.login('user@test.com', 'secret')
.then(dashboard => dashboard.openSettings())
.then(settings => settings.updateProfile());
Or with async/await:
const dashboard = await loginPage.login('user@test.com', 'secret');
const settings = await dashboard.openSettings();
Think Like a Journey Map
Each method returns the "destination" the user arrives at after that action. Login takes you to the dashboard. Opening settings takes you to the settings page. It mirrors how users think: "I log in, then I'm on the dashboard."
Key Takeaway: Return the next relevant Page Object from methods to create chainable, readable test flows that mirror actual user journeys through your application.