Playwright Test (JS/TS) - 공식 문서 기반
개요
이 스킬은 Playwright 문서에서 자주 실수하기 쉬운 내용들을 담고 있습니다: 자동 대기 규칙, strictness, 예상과 다르게 동작하는 타임아웃, 모킹의 사각지대, 스냅샷 업데이트 모드, CI 설정, 제거된 API 등. 일반적인 테스트 조언은 포함되지 않습니다. 모든 주장은 출처가 되는 문서 URL과 함께 제공되므로 확인할 수 있습니다.
적용 버전
Node.js 및 TypeScript 용 Playwright Test 1.64.1 (@playwright/test) 기준입니다. Python, Java, .NET 내용은 제외됩니다. 설치된 버전이 더 오래된 경우, 최신 API를 적용하기 전에 references/version-changes.md의 버전 표를 확인하세요.
탐색 방법
- 아래의 빠른 시작을 읽으세요. 대부분의 테스트에서 중요한 규칙들을 다룹니다.
- 작업 영역에 맞는 참조 파일 하나를 마지막 표에서 열어보세요.
- 기존 코드를 리뷰하거나 업그레이드하기 전에 아래 "이전 패턴"과
references/version-changes.md를 읽으세요.
빠른 시작
로케이터
- 기본:
page.getByRole(role, { name }). 그 다음getByLabel,getByText(비대화형 요소만),getByTestId를 계약 기반 대체 수단으로 사용. CSS나 XPath는 사용자에게 보이는 방법이 없을 때만 사용. https://playwright.dev/docs/locators#quick-guide - 로케이터는 strict합니다: 2개의 요소와 일치하는 로케이터에 액션을 수행하면 오류가 발생합니다.
first()/nth()대신filter({ hasText }),filter({ has })또는inner.within(outer)로 좁히세요. https://playwright.dev/docs/locators#strictness filter({ has })내부의 로케이터는 페이지 루트가 아닌 외부 일치 결과를 기준으로 해결됩니다. https://playwright.dev/docs/locators#filter-by-childdescendant- 텍스트 매칭은 기본적으로 부분 문자열(substring)이며 대소문자를 구분하지 않고, 항상 공백이 정규화됩니다.
exact: true인 경우도 마찬가지입니다. https://playwright.dev/docs/locators#locate-by-text
액션과 대기
- 액션은 작동 가능 상태(actionability)를 자동으로 기다립니다. 클릭 전에
waitForTimeout이나 수동 로드 대기를 추가하지 마세요. https://playwright.dev/docs/actionability#introduction 및 https://playwright.dev/docs/navigations#when-is-the-page-loaded fill()이 텍스트 입력의 기본입니다.pressSequentially()는 키 하나씩 처리해야 할 때만 사용하세요. https://playwright.dev/docs/input#type-characters- 이벤트(popup, download, filechooser, response): 클릭 전에 대기 promise를 만들고, 클릭 후에 await 하세요.
https://playwright.dev/docs/downloads#introductionconst downloadPromise = page.waitForEvent('download'); await page.getByText('Download file').click(); const download = await downloadPromise; dialog리스너가 수락(accept) 또는 거부(dismiss)하지 않으면 페이지가 중단됩니다. 리스너가 없으면 다이얼로그는 자동으로 해제됩니다. https://playwright.dev/docs/dialogs#alert-confirm-prompt-dialogs
어서션
- 항상
await expect(locator).toX()를 사용하세요.expect(await locator.isVisible()).toBe(true)는 한 번만 확인하므로 사용하지 마세요. https://playwright.dev/docs/best-practices#use-web-first-assertions - 어서션 타임아웃은 5초이며, 30초 테스트 타임아웃과 별개입니다. https://playwright.dev/docs/test-timeouts
- 일치하는 matcher가 없으면 기본적으로
expect.poll을 사용하세요.expect(...).toPass()는 기본 타임아웃이 없으므로 반드시 전달하세요. https://playwright.dev/docs/test-assertions#expecttopass - Jest의
expect가 아닌 Playwright의expect를 사용하세요. https://playwright.dev/docs/test-assertions#compatibility-with-expect-library
구조와 설정
- Runner 옵션은
defineConfig최상위 레벨에, 브라우저 및 컨텍스트 옵션은use내부에 넣습니다. https://playwright.dev/docs/test-configuration#introduction - before/after hook 쌍보다 fixture를 사용하세요. 테스트는 fixture 파일에서
test를 가져옵니다. https://playwright.dev/docs/test-fixtures#with-fixtures beforeAll은 worker당 한 번 실행되며, worker는 실패할 때마다 재시작되므로beforeAll이 여러 번 실행될 수 있습니다. https://playwright.dev/docs/test-retries#failuresdependencies를 사용하는 설정 프로젝트에서 한 번 로그인하고, 최종 URL을 기다린 후storageState를 저장하고,playwright/.auth를 gitignore에 추가하세요. https://playwright.dev/docs/auth#basic-shared-account-in-all-tests- device를 먼저 펼친(spread) 후
viewport를 재정의하세요. device 자체도 자체viewport를 정의하기 때문입니다. https://playwright.dev/docs/emulation#viewport - Playwright는 타입 검사를 수행하지 않습니다. CI에서
tsc --noEmit을 실행하고@typescript-eslint/no-floating-promises로 린트하세요. https://playwright.dev/docs/test-typescript#introduction 및 https://playwright.dev/docs/best-practices#lint-your-tests
네트워크
page.route를page.goto보다 먼저 등록하세요. Glob 패턴은 전체 URL과 일치해야 하며,?는 리터럴 물음표만 일치시킵니다. https://playwright.dev/docs/mock#mock-api-requests 및 https://playwright.dev/docs/network#glob-url-patterns- 라우트는 서비스 워커가 처리하는 요청을 놓칠 수 있습니다.
serviceWorkers: 'block'을 설정하세요. https://playwright.dev/docs/network#missing-network-events-and-service-workers page.request는 브라우저 쿠키를 공유합니다.request.newContext()는 격리되어 있으며 해제(dispose)되어야 합니다. https://playwright.dev/docs/api-testing#context-request-vs-global-request
CI
forbidOnly: !!process.env.CI,retries: process.env.CI ? 2 : 0,workers: process.env.CI ? 1 : undefined,trace: 'on-first-retry', 그리고 항상globalTimeout을 설정하세요. 그렇지 않으면 중단된 실행이 리포트를 생성하지 않습니다. https://playwright.dev/docs/test-configuration#basic-configuration 및 https://playwright.dev/docs/ci#global-timeoutnpm ci후 그리고 모든 업그레이드 후에npx playwright install --with-deps를 실행하세요. 브라우저를 캐시하지 마세요. https://playwright.dev/docs/ci#caching-browsersfullyParallel: true로 샤딩하고 blob 리포트를 병합하세요. https://playwright.dev/docs/test-sharding#balancing-shards- 리소스를 공유하는 테스트는 직렬 모드가 아닌 테스트 락(lock)으로 직렬화하세요:
test('x', { lock: 'db' }, ...). https://playwright.dev/docs/test-parallel#test-locks
스냅샷
-u없이, 누락된 스냅샷이 기록(write)되고 테스트는 실패합니다.--update-snapshots=missing은 기록하고 통과합니다.-u는changed를 의미합니다. https://playwright.dev/docs/aria-snapshots#updating-snapshots-with-playwrighttest-and-the---update-snapshots-flag- 스크린샷 기준(baselines)은 브라우저와 OS별로 다릅니다. 비교할 환경에서 생성하세요. https://playwright.dev/docs/test-snapshots#introduction
이전 패턴
참조 파일
| 파일 | 읽을 내용 |
|---|---|
| references/locators.md | 로케이터 우선순위, 텍스트 매칭, strictness, filter, within, and / or, visible(), Shadow DOM, 프레임, 레거시 선택자 |
| references/actions-and-events.md | 액션별 작동 가능성 검사, force, 입력, 드래그 앤 드롭, 다이얼로그, 다운로드, 업로드, 팝업, 탐색, hydration, evaluate, 초기화 스크립트, 핸들 |
| references/assertions.md | 웹 퍼스트 vs 일반 matcher, 어서션 타임아웃, expect.poll, toPass, 소프트 어서션, 커스텀 matcher, test.step |
| references/snapshots-and-accessibility.md | 스냅샷 업데이트 모드, aria 스냅샷, toHaveScreenshot 허용 오차 및 이름 지정, 비이미지 스냅샷, axe 검사 |
| references/configuration.md | 설정 구조, use 범위와 기본값, 프로젝트 및 종속성, device 및 에뮬레이션, TypeScript 처리, webServer |
| references/timeouts-retries-annotations.md | 모든 타임아웃과 기본값, 재시도 및 worker 재시작, 직렬 모드, skip / fail / fixme, 태그, 매개변수화된 테스트와 프로젝트 |
| references/fixtures-and-auth.md | 격리, 커스텀 fixture, 범위, 옵션, 실행 순서, 글로벌 훅, 설정 프로젝트, 페이지 객체, storageState 인증, 역할, worker당 계정 |
| references/network-and-mocking.md | route, glob 규칙, 라우트가 건드릴 수 없는 헤더와 리디렉션, HAR 기록 및 재생, WebSocket 모의, 브라우저 API 모의, 서비스 워커 |
| references/api-testing-and-clock.md | request fixture, 공유 vs 격리된 쿠키, 컨텍스트 해제, page.clock 메서드 및 순서 |
| references/ci-parallel-sharding.md | CI 기준, GitHub Actions 및 기타 제공자, workers, fullyParallel, 테스트 락, 샤딩, blob 리포트 병합 |
| references/browsers-and-docker.md | 브라우저 설치 및 캐시, Chromium 채널, 프록시 및 미러, Docker 이미지, Chrome 확장 프로그램, WebView2, Selenium Grid |
| references/debugging-and-reporting.md | CLI 플래그, --debug, Inspector, 트레이스 및 비디오 모드, 트레이스 뷰어, UI 모드, 리포터 |
| references/component-testing-and-migration.md | 스토리 및 갤러리 컴포넌트 테스트, 실험적 ct 패키지, Testing Library, Protractor, Puppeteer에서 마이그레이션 |
| references/codegen-and-agent-tooling.md | codegen, Library vs Test, 릴리스 채널, Test Agent, playwright-cli, Playwright MCP |
| references/version-changes.md | 주요 동작 변경, 제거 및 비활성화된 API와 대체 방법, 플랫폼 지원 변경사항 |
출처 및 가져오기 세부 사항은 SOURCES.md에 나열되어 있습니다.