Playwright hỗ trợ storageState để save và reuse authentication state giữa tests.
- Pattern: globalSetup.ts chạy một lần trước tất cả tests — login qua UI hoặc API, save state: await context.storageState({ path: 'auth/user.json' }).
- Reuse trong playwright.config.ts: use: { storageState: 'auth/user.json' } — mỗi test bắt đầu đã authenticated, không phải login lại.
- Multiple roles: save different storageStates cho admin, regular user, guest — dùng projects trong config để chạy same tests với different roles.
- API-based auth nhanh hơn UI login: const response = await request.post('/api/login', { data: { email, password } }); await page.context().addCookies([...]) — avoid UI flakiness.
- Page Object Model (POM): class LoginPage { constructor(page) {...}; async login(email, pw) { await this.page.fill('#email', email); ... } } — encapsulate page interactions, reusable across tests, easy maintenance khi UI thay đổi.
- Fixtures trong Playwright: custom fixtures extend base test với pre-setup state — const test = base.extend({ loggedInPage: async ({page}, use) => { await loginUser(page); await use(page); } }) — elegant và composable.
- Avoid test interdependency: mỗi test phải independent, không phụ thuộc vào state từ test trước — dùng beforeEach để reset state.