アクションメソッドの作成
アクションメソッドの作成
Page Objectでアクション(操作)をメソッドとして定義する方法を学びます。
アクションメソッドとは?
ページ上での操作をまとめたメソッドです。
// 複数の操作を1つのメソッドにまとめる
async login(username: string, password: string) {
await this.usernameInput.fill(username);
await this.passwordInput.fill(password);
await this.loginButton.click();
}
よくあるアクションメソッド
ページ遷移
async goto() {
await this.page.goto('/login');
}
async gotoWithParams(returnUrl: string) {
await this.page.goto(`/login?returnUrl=${returnUrl}`);
}
フォーム入力
async fillLoginForm(username: string, password: string) {
await this.usernameInput.fill(username);
await this.passwordInput.fill(password);
}
async submit() {
await this.submitButton.click();
}
// 入力と送信をまとめる
async login(username: string, password: string) {
await this.fillLoginForm(username, password);
await this.submit();
}
情報の取得
async getErrorMessage(): Promise<string> {
return await this.errorMessage.textContent() ?? '';
}
async isLoggedIn(): Promise<boolean> {
return await this.logoutButton.isVisible();
}
async getWelcomeText(): Promise<string> {
return await this.welcomeMessage.textContent() ?? '';
}
待機を含む操作
async loginAndWaitForDashboard(username: string, password: string) {
await this.login(username, password);
await this.page.waitForURL('/dashboard');
}
async loginAndWaitForError(username: string, password: string) {
await this.login(username, password);
await this.errorMessage.waitFor({ state: 'visible' });
}
完成例
import { Page, Locator } from '@playwright/test';
export class LoginPage {
readonly page: Page;
readonly usernameInput: Locator;
readonly passwordInput: Locator;
readonly loginButton: Locator;
readonly errorMessage: Locator;
constructor(page: Page) {
this.page = page;
this.usernameInput = page.locator('#username');
this.passwordInput = page.locator('#password');
this.loginButton = page.getByRole('button', { name: 'Login' });
this.errorMessage = page.locator('.error-message');
}
// ナビゲーション
async goto() {
await this.page.goto('/login');
}
// フォーム操作
async fillForm(username: string, password: string) {
await this.usernameInput.fill(username);
await this.passwordInput.fill(password);
}
async submit() {
await this.loginButton.click();
}
async login(username: string, password: string) {
await this.fillForm(username, password);
await this.submit();
}
// 情報取得
async getErrorMessage(): Promise<string> {
return await this.errorMessage.textContent() ?? '';
}
async hasError(): Promise<boolean> {
return await this.errorMessage.isVisible();
}
}
💡 命名のコツ
- 動詞で始める:
login,fill,submit,click - getで始める(情報取得):
getErrorMessage,getText - is/hasで始める(真偽値):
isVisible,hasError