
selenium에서도 검증을 위한 방법으로 Assertion을 사용했었는데 Playwright에서도 동일하게 Assertion을 사용해서 기댓값에 알맞은지 검증하는 방법에 관한 포스팅을 작성해 보겠습니다. 모든 예시문은 JavaScript를 사용해서 작성되었습니다.
2022.08.13 - [자동화(Automation)/Selenium] - Selenium_Assert&Verify
보통 테스트문을 작성할때 가장 많이 사용하는 방법이 title이나 URL, string키의 비교이기 때문에 크게 3가지 방법의 예시를 가져와 봤습니다. playwright 문서에 이 외에도 다양한 케이스들이 나와있기 때문에 한번 참고해서 상황에 맞게 테스트문을 작성하시기를 권장합니다.
참고사이트 : https://playwright.dev/docs/test-assertions
Assertions | Playwright
Introduction
playwright.dev
1. Title Assertions
const { chromium } = require('playwright');
const { expect } = require('@playwright/test');
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
// 방법 1: 직접 비교
const title = await page.title();
if (title === 'Example Domain') {
console.log('타이틀이 일치합니다!');
}
// 방법 2: expect를 사용한 검증 (Playwright Test 사용 시)
await expect(page).toHaveTitle('Example Domain');
// 방법 3: 부분 일치 확인 (정규표현식)
await expect(page).toHaveTitle(/Example/);
await browser.close();
})();
Assertion의 방법으로는 크게 3가지가 있는데 아래와 같습니다.
1. 열린 페이지에 타이틀을 직접 비교하는 방법
2. expect를 사용해서 검증 전체 타이틀 문구를 비교하는 방법
3. expect를 사용해서 부분적으로 일치하는지 확인하는 방법
2. URL 검증
// 1. 정확한 전체 URL
await expect(page).toHaveURL('https://example.com/signup');
// 2. 경로만 확인
await expect(page).toHaveURL(/\/signup$/);
// 3. 특정 단어 포함 여부
await expect(page).toHaveURL(/signup/);
// 4. URL의 특정 부분만 확인
const url = new URL(page.url());
expect(url.pathname).toBe('/signup');
expect(url.hostname).toBe('example.com');
// 5. 쿼리 파라미터 확인
await page.goto('https://example.com/search?q=test');
expect(page.url()).toContain('q=test');
// 6. 해시(#) 확인
await page.goto('https://example.com/page#section1');
expect(page.url()).toContain('#section1');
URL도 타이틀 검증과 비슷한 방법으로 기본적으로는 expect().toHaveURL을 사용해서 전체 URL이나 경로, 특정 단어가 포함되는지를 검증하는 방법을 사용합니다. 하지만 경우에 따라 URL의 특정 부분만 확인할 수도 있는데 이는 URL 형식에 따라 쿼리나 해시를 확인하는 방식으로 이용할 수도 있습니다.
3. 문자열 검증방법
const { test, expect } = require('@playwright/test');
test('주문 확인 페이지 전체 검증', async ({ page }) => {
await page.goto('https://example.com/checkout/confirm');
// 예상 데이터
const expectedData = {
productName: '노트북 15인치',
price: '1,200,000원',
quantity: '2개',
shippingFee: '무료',
totalAmount: '2,400,000원'
};
// 상품명 검증
const productName = await page.locator('[data-testid="product-name"]').textContent();
expect(productName?.trim()).toBe(expectedData.productName);
// 가격 검증
const price = await page.locator('[data-testid="product-price"]').textContent();
expect(price?.trim()).toBe(expectedData.price);
// 수량 검증
const quantity = await page.locator('[data-testid="quantity"]').textContent();
expect(quantity?.trim()).toBe(expectedData.quantity);
// 배송비 검증
await expect(page.getByText(expectedData.shippingFee)).toBeVisible();
// 총 금액 검증
const totalAmount = await page.locator('[data-testid="total-amount"]').textContent();
expect(totalAmount?.trim()).toBe(expectedData.totalAmount);
console.log('모든 주문 정보가 일치합니다!');
});
보통 저의 경우에는 주문/결제 테스트에서 문자열을 확인하는 검증을 많이 사용하는데, 고정 상품을 판매하는 경우에는 가격이나 상품명의 변경이 자주 일어나지 않기 때문입니다.
그래서 문자열을 통해 주문내역을 확인할때에는 expectedData에 주문할 상품의 정보를 넣어두고 expect문을 통해 검증하는 테스트문을 작성하는 방법을 사용하는 것이 편리합니다.
반면에 숫자 확인이 필요한 경우에는, 문자열에서 숫자만을 분리하는 방법을 사용해서 가격이 맞는지 확인하는 테스트문을 작성할 수 있습니다.
const { test, expect } = require('@playwright/test');
test('금액 계산 검증', async ({ page }) => {
await page.goto('https://example.com/cart');
// 가격 텍스트 가져오기
const priceText = await page.locator('.unit-price').textContent();
const quantityText = await page.locator('.quantity').textContent();
const totalText = await page.locator('.total-price').textContent();
// 문자열에서 숫자만 추출
const price = parseInt(priceText?.replace(/[^0-9]/g, '') || '0');
const quantity = parseInt(quantityText?.replace(/[^0-9]/g, '') || '0');
const total = parseInt(totalText?.replace(/[^0-9]/g, '') || '0');
// 계산 검증
expect(total).toBe(price * quantity);
console.log(`단가: ${price}, 수량: ${quantity}, 합계: ${total}`);
});
4. Soft assertions
마지막으로는 soft assertion 사용방법입니다.
보통 테스트 검증에 실패한 경우에는 테스트 실행을 종료합니다. 하지만 soft assertions를 사용하면 테스트 실행을 종료시키지 않고 실패한 것으로만 표시하고 계속 진행하는 방법입니다. 그래서 테스트 실패시 바로 종료되지 않고 계속 이어서 진행하길 원한다면 soft assertion을 사용하면 된다.
// Make a few checks that will not stop the test when failed...
await expect.soft(page.getByTestId('status')).toHaveText('Success');
await expect.soft(page.getByTestId('eta')).toHaveText('1 day');
// Avoid running further if there were soft assertion failures.
expect(test.info().errors).toHaveLength(0);
하지만, 실패 케이스에 대한 확인이 필요하다면 해당 expect(test.info().errors).toHaveLength(0);문을 통해서 soft assertion으로 실패가 있었는지 검증 확인이 가능합니다.
'자동화(Automation) > Playwright' 카테고리의 다른 글
| Playwright_Annotations, Hooks, Fixtures (0) | 2025.10.17 |
|---|---|
| Playwright 자동화 Introduction (+window 환경에서 playwright 설치) (0) | 2025.09.28 |