MOC

Keywords

  • Selector
  • Actions
  • Assertions
  • Fixtures
  • Page
  • Locator
  • test runner.

1. Core Concepts

KeywordÝ nghĩa nhanh
Browser / Context / Page3 tầng cốt lõi: Browser (instance) → Context (session, cookies, storage) → Page (tab)
LocatorCách xác định element ổn định (thay vì dùng selector thủ công)
Test Runner@playwright/test – framework tích hợp sẵn: chạy test, fixture, reporter
FixtureCách chuẩn bị môi trường & chia sẻ state cho test
POM (Page Object Model)Tách logic thao tác UI ra khỏi test, giúp code dễ bảo trì

2. Test API chính

KeywordÝ nghĩa
test()Định nghĩa một test
test.describe()Gom nhóm test logic
beforeEach / afterEachHook setup/teardown
expect()Assertion API (toBeVisible, toHaveText, toHaveURL, …)
page.goto()Mở trang
page.locator()Lấy element để thao tác
locator.click() / fill() / press() / selectOption()Tương tác UI
page.context().storageState()Lưu auth state để bỏ qua bước login
test.use()Cấu hình per-test (browser, storage state, viewport, …)

3. Selector & Locator Strategy

KeywordÝ nghĩa nhanh
getByRole()Ưu tiên số 1 (ổn định, semantic)
getByText()Tìm theo nội dung
getByTestId()Rất tốt khi bạn thêm data-testid vào HTML
locator(css)Fallback khi không có lựa chọn tốt hơn
Chờ implicitPlaywright auto-wait → không cần sleep

4. Debug

KeywordÝ nghĩa nhanh
npx playwright codegenGhi lại hành động → tạo script nhanh
page.pause()Dừng giữa chừng để debug
--debugMở UI debugger
Trace ViewerGhi log + DOM snapshot từng bước test
slowMo, headless: falseTùy chọn chạy test dễ nhìn khi debug

Locator

  • page.getByRole, page.getByText, locator('[data-testid="x"]')

Action

  • click, fill, type, press, check, selectOption, hover

Assertions

  • expect(locator).toBeVisible()
  • expect(page).toHaveURL()
  • toHaveText, toContainText, toHaveAttribute

Fixtures & hooks

  • beforeEach, afterEach
  • Custom fixtures cho login sẵn, setup dữ liệu

Code structure

  • Tách Page Object Models (POM) đơn giản để test không bị lặp code

Automation

  • Authentication shortcut: Đăng nhập Lưu State vào localstorage

  • Debug

    • npx playwright test —debug
    • page.pause()
    • Trace viewer (npx playwright show-trace)
  • Parallel & retries

    • retries, workers, projects (multi-browser)
    • Filter test bằng tags

Run command

# Run all tests
npx playwright test

# Run tests in a specific file
npx playwright test tests/example.spec.ts

# Run a specific test by name
npx playwright test --grep "has title"

# Run tests in headed mode (see the browser)
npx playwright test --headed

# Run tests in debug mode
npx playwright test --debug

# Run tests on a specific browser
npx playwright test --project chromium

# Run tests with UI mode
npx playwright test --ui

# Show the HTML report after tests run
npx playwright show-report

References