[Playwright Interview question #8]: Page Object Model trong Playwright được implement như thế nào?
Câu hỏi phỏng vấn #8: Page Object Model trong Playwright được implement như thế nào?
Trả lời mẫu:
Page Object Model (POM) là design pattern phổ biến trong test automation:
1. Basic Page Object:
// pages/login.page.ts
export class LoginPage {
constructor(page) {
this.page = page;
this.usernameInput = page.locator('#username');
this.passwordInput = page.locator('#password');
this.loginButton = page.locator('#login-btn');
}
async login(username, password) {
await this.usernameInput.fill(username);
await this.passwordInput.fill(password);
await this.loginButton.click();
}
}
2. Sử dụng trong test:
// tests/login.spec.js
import { LoginPage } from '../pages/LoginPage';
test('user can login', async ({ page }) => {
const loginPage = new LoginPage(page);
await page.goto('/login');
await loginPage.login('user@test.com', 'password123');
});
3. Advanced POM với getters:
export class ProductPage {
constructor(page) {
this.page = page;
}
get addToCartButton() {
return this.page.locator('[data-test="add-to-cart"]');
}
get productTitle() {
return this.page.locator('.product-title');
}
}
💡 Tips:
- Mỗi page = 1 class riêng
- Store locators as properties hoặc getters
- Methods represent user actions
- Reuse page objects across multiple tests
- Keep page objects focused và single responsibility
Lời Kết
Playwright đang trở thành một trong những automation frameworks phổ biến nhất cho web testing. Thông qua series này, hy vọng bạn sẽ:
- Nắm vững kiến thức từ cơ bản đến nâng cao
- Tự tin trong các buổi phỏng vấn
- Áp dụng hiệu quả vào dự án thực tế
- Trở thành một phần của cộng đồng Playwright Việt Nam năng động
📚 Bắt đầu hành trình của bạn với: Bài 1: Playwright vs Selenium
💬 Có câu hỏi? Tham gia group Facebook của chúng mình!
⭐ Theo dõi series để không bỏ lỡ bài viết mới!
All rights reserved