Bài Tập 2: Tạo ShopPage¶
Yêu Cầu¶
Tạo Page Object cho trang Shop trên Practice Website.
Hướng Dẫn¶
Bước 1: Tạo file¶
Tạo file pages/ShopPage.ts
Bước 2: Viết Page Object¶
// pages/ShopPage.ts
import { Page, Locator, expect } from '@playwright/test';
export class ShopPage {
readonly page: Page;
// TODO: Khai báo locator
readonly searchInput: Locator;
readonly productTitle: Locator;
constructor(page: Page) {
this.page = page;
// TODO: Khởi tạo locator
this.searchInput = page.locator('_______________');
this.productTitle = page.locator('_______________');
}
// TODO: Method mở trang
async goto() {
await this.page.goto('_______________');
}
// TODO: Method tìm kiếm sản phẩm
async searchProduct(keyword: string) {
await this.searchInput.fill(keyword);
await this.searchInput.press('Enter');
}
// TODO: Method click vào sản phẩm
async clickProduct(name: string) {
await this.page.locator(`text=${name}`).click();
}
// TODO: Assertion sản phẩm visible
async expectProductVisible(name: string) {
await expect(this.page.locator(`text=${name}`)).toBeVisible();
}
}
Bước 3: Tìm locator¶
Dùng DevTools tìm locator cho:
- Ô tìm kiếm: _____
- Sản phẩm (title): _____
Bước 4: Test Page Object¶
Tạo file test để kiểm tra:
// tests/test-shop-page.spec.ts
import { test, expect } from '@playwright/test';
import { ShopPage } from '../pages/ShopPage';
test('test shop page object', async ({ page }) => {
const shopPage = new ShopPage(page);
await shopPage.goto();
await shopPage.searchProduct('Android');
await shopPage.expectProductVisible('Android');
});
Checklist¶
□ File ShopPage.ts được tạo
□ Tất cả locator được khai báo
□ Method goto() hoạt động
□ Method searchProduct() hoạt động
□ Method clickProduct() hoạt động
□ Assertion expectProductVisible() hoạt động
□ Test pass
Gợi ݶ
Click để xem solution
// pages/ShopPage.ts
import { Page, Locator, expect } from '@playwright/test';
export class ShopPage {
readonly page: Page;
readonly searchInput: Locator;
readonly productTitle: Locator;
constructor(page: Page) {
this.page = page;
this.searchInput = page.locator('#s');
this.productTitle = page.locator('.product-title');
}
async goto() {
await this.page.goto('https://practice.automationtesting.in/shop/');
}
async searchProduct(keyword: string) {
await this.searchInput.fill(keyword);
await this.searchInput.press('Enter');
}
async clickProduct(name: string) {
await this.page.locator(`text=${name}`).click();
}
async expectProductVisible(name: string) {
await expect(this.page.locator(`text=${name}`)).toBeVisible();
}
}
Nộp Bài¶
- [ ] File ShopPage.ts hoàn chỉnh
- [ ] File test kiểm tra
- [ ] Test pass