Course contentsShow
← React
Lesson 2195 of 2,39648. End-to-End TestingFree lesson

Encapsulating Actions: Methods for User Flows

Creating methods like login(), submitForm(), and clickButton() that hide low-level Playwright/Cypress commands.

Encapsulating Actions: Methods for User Flows

You'll learn how to hide low-level Playwright/Cypress commands inside reusable methods that describe what the user is actually doing.

The Problem with Scattered Commands

In the previous lesson, you learned to encapsulate locators in page object classes. But your tests still contain scattered commands like await page.locator('[data-testid="email"]').fill('user@example.com'). This makes tests verbose and couples them to implementation details.

Methods That Tell a Story

The solution is creating methods that represent complete user actions:

class LoginPage {
  constructor(page) {
    this.page = page;
    this.emailInput = page.getByLabel('Email');
    this.passwordInput = page.getByLabel('Password');
    this.submitButton = page.getByRole('button', { name: 'Sign In' });
  }

  async login(email, password) {
    await this.emailInput.fill(email);
    await this.passwordInput.fill(password);
    await this.submitButton.click();
  }
}

Now your test reads like a user story:

test('successful login redirects to dashboard', async ({ page }) => {
  const loginPage = new LoginPage(page);
  await loginPage.login('user@example.com', 'password123');
  
  await expect(page).toHaveURL('/dashboard');
});

The Abstraction Advantage

Think of it like a remote control: you press "Record" instead of manually configuring channels, timers, and input sources. Similarly, login() hides the mechanical details of filling fields and clicking buttons.

These methods create a domain-specific language for your tests. Instead of thinking "fill this input, click that button," you think "log in as this user."

Key Takeaway: Encapsulating user flows in methods like login(), submitForm(), and clickButton() makes tests readable, maintainable, and resilient to UI changes—you only update the page object, not every test.