Skip to content

建立 2026-09-15 更新 2026-09-15

Page Object Model

Page Object Model(POM,頁面物件模型)是一種常見的測試程式碼組織方式:把「如何操作某個頁面」封裝成一個類別,測試案例只呼叫方法、不直接處理 Locator 細節。當畫面改版時,只需要修改對應的 Page Object,不用逐一修改每一支測試。

基本寫法

// pages/LoginPage.ts
import { expect, type Locator, type Page } from '@playwright/test';

export class LoginPage {
  readonly page: Page;
  readonly usernameInput: Locator;
  readonly passwordInput: Locator;
  readonly submitButton: Locator;

  constructor(page: Page) {
    this.page = page;
    this.usernameInput = page.getByLabel('帳號');
    this.passwordInput = page.getByLabel('密碼');
    this.submitButton = page.getByRole('button', { name: '登入' });
  }

  async goto() {
    await this.page.goto('/login');
  }

  async login(username: string, password: string) {
    await this.usernameInput.fill(username);
    await this.passwordInput.fill(password);
    await this.submitButton.click();
  }

  async expectLoggedIn() {
    await expect(this.page.getByText('歡迎回來')).toBeVisible();
  }
}
// login.spec.ts
import { test } from '@playwright/test';
import { LoginPage } from './pages/LoginPage';

test('使用正確帳密可以登入', async ({ page }) => {
  const loginPage = new LoginPage(page);
  await loginPage.goto();
  await loginPage.login('demo@vcdemy.com', 'password123');
  await loginPage.expectLoggedIn();
});

測試案例讀起來像是操作步驟的描述(gotologinexpectLoggedIn),不需要理解 Locator 細節,這對非技術背景的團隊成員(例如 QA、PM)閱讀測試也更友善。

搭配 Fixture 自動建立 Page Object

結合 Fixtures 與 Hooks,可以讓測試直接拿到已經建立好的 Page Object,不用每個測試手動 new

// fixtures.ts
import { test as base } from '@playwright/test';
import { LoginPage } from './pages/LoginPage';

type Pages = { loginPage: LoginPage };

export const test = base.extend<Pages>({
  loginPage: async ({ page }, use) => {
    await use(new LoginPage(page));
  },
});
test('使用 fixture 版本', async ({ loginPage }) => {
  await loginPage.goto();
  await loginPage.login('demo@vcdemy.com', 'password123');
  await loginPage.expectLoggedIn();
});

什麼時候該用 POM?

  • 適合:頁面操作會被多個測試重複使用(例如登入、搜尋、加入購物車),或畫面結構複雜、Locator 較多。
  • 不一定需要:只有一兩個簡單測試、頁面操作單純時,直接在測試裡寫 Locator 反而更直觀,不必為了套用模式而過度封裝。

Playwright 官方文件本身也提醒:POM 是一種可選的組織方式,不是強制規範,團隊應依專案規模決定要不要採用,以及封裝到什麼程度。

下一步

了解如何組織測試程式碼後,接著看 設定檔與多瀏覽器/裝置,學習如何用 playwright.config.ts 統一管理整個專案的測試行為。