🎭 Playwright · 레슨 4 / 7

Playwright 픽스처와 페이지 객체 — test.extend로 준비 코드를 재사용하기

페이지 객체 모델(POM)로 로케이터와 동작을 클래스로 묶고, test.extend로 사용자 정의 픽스처를 만들어 준비·정리 코드를 재사용하는 방법, 워커 범위 픽스처와 옵션 픽스처, 테스트 데이터 정리 패턴을 배웁니다.

⏱ 약 5분🗓 2026-11-13 업데이트🏷 Playwright 1.x 기준

이 레슨에서 배우는 것

  • 페이지 객체 클래스로 로케이터와 동작을 한곳에 모으기
  • test.extend로 사용자 정의 픽스처 만들기
  • 테스트 범위·워커 범위 픽스처를 구분해 쓰기

왜 구조가 필요한가

테스트가 수십 개로 늘면 같은 로케이터와 준비 코드(로그인, 데이터 생성)가 여러 파일에 복사됩니다. 화면이 바뀌면 그 복사본을 모두 고쳐야 합니다. Playwright는 두 가지 도구로 이를 해결합니다.

페이지 객체 만들기

tests/pages/todo-page.tstypescript
import { expect, type Locator, type Page } from '@playwright/test';

export class TodoPage {
  readonly newTodo: Locator;
  readonly items: Locator;
  readonly titles: Locator;
  readonly counter: Locator;

  constructor(private readonly page: Page) {
    this.newTodo = page.getByPlaceholder('What needs to be done?');
    this.items = page.getByTestId('todo-item');
    this.titles = page.getByTestId('todo-title');
    this.counter = page.getByTestId('todo-count');
  }

  async goto() {
    await this.page.goto('/todomvc');
  }

  async add(...texts: string[]) {
    for (const t of texts) {
      await this.newTodo.fill(t);
      await this.newTodo.press('Enter');
    }
  }

  item(text: string) {
    return this.items.filter({ hasText: text });
  }

  async complete(text: string) {
    await this.item(text).getByRole('checkbox').check();
  }

  async filter(name: 'All' | 'Active' | 'Completed') {
    await this.page.getByRole('link', { name }).click();
  }

  async expectTitles(titles: string[]) {
    await expect(this.titles).toHaveText(titles);
  }
}
✅
페이지 객체에 넣을 것과 뺄 것

로케이터와 사용자 동작은 페이지 객체에, 무엇을 검증할지는 테스트에 두는 것이 기본입니다. 여러 테스트가 반복하는 검증만 expectTitles처럼 도우미로 둡니다.

test.extend로 픽스처 만들기

페이지 객체를 테스트마다 new TodoPage(page)로 만들 필요 없이, 픽스처로 주입합니다.

tests/fixtures.tstypescript
import { test as base } from '@playwright/test';
import { TodoPage } from './pages/todo-page';

type Fixtures = {
  todoPage: TodoPage;
};

export const test = base.extend<Fixtures>({
  todoPage: async ({ page }, use) => {
    const todoPage = new TodoPage(page);   // 준비
    await todoPage.goto();
    await use(todoPage);                   // 테스트 실행
    // use 이후는 정리 코드 (테스트가 실패해도 실행됨)
  },
});

export { expect } from '@playwright/test';
tests/todo.spec.tstypescript
import { test, expect } from './fixtures';

test('완료 필터', async ({ todoPage }) => {
  await todoPage.add('우유 사기', '책 읽기', '운동');
  await todoPage.complete('책 읽기');
  await todoPage.filter('Completed');
  await todoPage.expectTitles(['책 읽기']);
});

test('남은 개수', async ({ todoPage }) => {
  await todoPage.add('우유 사기', '책 읽기');
  await todoPage.complete('우유 사기');
  await expect(todoPage.counter).toHaveText('1 item left');
});

테스트 데이터 픽스처: 만들고 지우기

실제 서비스 테스트에서는 API로 데이터를 만들고 끝나면 지우는 픽스처가 유용합니다. 화면을 거치지 않으니 빠르고, 정리 코드가 보장되어 데이터가 쌓이지 않습니다.

typescript
type Fixtures = { project: { id: string; name: string } };

export const test = base.extend<Fixtures>({
  project: async ({ request }, use, testInfo) => {
    const name = `e2e-${testInfo.workerIndex}-${Date.now()}`;
    const res = await request.post('/api/projects', { data: { name } });
    const project = await res.json();

    await use(project);

    await request.delete(`/api/projects/${project.id}`);
  },
});

test('프로젝트 이름 변경', async ({ page, project }) => {
  await page.goto(`/projects/${project.id}/settings`);
  // ...
});

이름에 workerIndex와 시각을 넣으면 병렬 워커끼리 데이터가 겹치지 않습니다.

워커 범위 픽스처와 옵션

기본 픽스처는 테스트마다 새로 만들어집니다(scope: 'test'). DB 연결이나 테스트 계정처럼 비싸고 공유해도 되는 자원은 워커 범위로 만들어 워커 프로세스당 한 번만 준비합니다.

typescript
type WorkerFixtures = { account: { email: string; password: string } };
type Options = { locale: string };

export const test = base.extend<Options, WorkerFixtures>({
  // 설정 파일에서 값을 바꿀 수 있는 옵션 픽스처
  locale: ['ko-KR', { option: true }],

  account: [async ({}, use, workerInfo) => {
    const account = await createTestAccount(`worker${workerInfo.workerIndex}`);
    await use(account);
    await deleteTestAccount(account);
  }, { scope: 'worker' }],
});
playwright.config.ts (projects 일부)typescript
projects: [
  { name: 'ko', use: { locale: 'ko-KR' } },
  { name: 'en', use: { locale: 'en-US' } },
],
💡
자동 픽스처

{ auto: true }를 주면 테스트가 요청하지 않아도 모든 테스트에서 실행됩니다. 실패 시 콘솔 로그를 첨부하거나 공통 모킹을 거는 용도로 씁니다.

정리