콘텐츠로 이동

Playwright 열 시트

Playwright - 현대 웹 테스트 및 자동화

Playwright는 웹 테스트 및 자동화를위한 프레임 워크입니다. 단일 API로 Chromium, Firefox 및 WebKit을 테스트 할 수 있습니다. Playwright는 빠르고 신뢰할 수있는 크로스 브라우져 웹 자동화를 가능하게합니다.

본문 바로가기

설치하기

기본 설치

카지노사이트

시스템 의존

카지노사이트

프로젝트 설정

카지노사이트

구성 파일

카지노사이트

시작하기

기본 시험 구조

카지노사이트

시험 실행

카지노사이트

시험 Hooks

카지노사이트

브라우저 관리

브라우저 설정

카지노사이트

브라우저 실행 옵션

카지노사이트

여러 브라우저

카지노사이트

관련 기사

기본 정보

ο 회원 관리

전략 계획

카지노사이트

URL 및 제목 등록

카지노사이트

성분 상호 작용

클릭 요소

카지노사이트

양식 상호 작용

카지노사이트

키보드 및 마우스 동작

카지노사이트

회사 소개

CSS 선택기

카지노사이트

텍스트 선택기

카지노사이트

역할 기반 선택자

카지노사이트

Playwright 로케이터

오프화이트

고급 선택자

카지노사이트

대기 전략

요소 대기

오프화이트

자동 waiting

카지노사이트

주문 대기

카지노사이트

회사연혁

입력 필드

카지노사이트

드롭다운 선택

카지노사이트

체크박스 및 라디오 버튼

카지노사이트

파일 업로드

카지노사이트

양식 제출

```javascript test('form submission', async ({ page }) => { await page.goto('https://example.com/form');

// Fill form await page.fill('#username', 'testuser'); await page.fill('#email', 'test@example.com'); await page.fill('#password', 'password123'); await page.check('#agree-terms');

// Submit form by clicking submit button await Promise.all([ page.waitForNavigation(), page.click('#submit-button') ]);

// Submit form by pressing Enter await Promise.all([ page.waitForNavigation(), page.press('#username', 'Enter') ]);

// Submit form programmatically await page.evaluate(() => { document.querySelector('#form').submit(); });

// Verify form submission await expect(page).toHaveURL(/success/); await expect(page.locator('.success-message')).toBeVisible(); }); ```의 경우

스크린 샷 & 동영상

스크린샷

```javascript test('screenshots', async ({ page }) => { await page.goto('https://example.com');

// Full page screenshot await page.screenshot({ path: 'screenshots/fullpage.png' });

// Screenshot with options await page.screenshot({ path: 'screenshots/page.png', fullPage: true, clip: { x: 0, y: 0, width: 800, height: 600 }, quality: 80, type: 'jpeg' });

// Element screenshot await page.locator('#header').screenshot({ path: 'screenshots/header.png' });

// Screenshot to buffer const buffer = await page.screenshot();

// Screenshot with mask await page.screenshot({ path: 'screenshots/masked.png', mask: [page.locator('.sensitive-data')] });

// Mobile screenshot await page.setViewportSize({ width: 375, height: 667 }); await page.screenshot({ path: 'screenshots/mobile.png' }); }); ```에 대하여

동영상 녹화

```javascript // playwright.config.js export default defineConfig({ use: { // Record video for all tests video: 'on',

// Record video only on failure
video: 'retain-on-failure',

// Record video on first retry
video: 'on-first-retry',

}, });

test('video recording', async ({ page }) => { // Video is automatically recorded based on config await page.goto('https://example.com'); await page.click('#button'); await page.fill('#input', 'test');

// Video will be saved to test-results folder }); ```의 경우

비주얼 비교

```javascript test('visual comparisons', async ({ page }) => { await page.goto('https://example.com');

// Compare full page await expect(page).toHaveScreenshot('homepage.png');

// Compare element await expect(page.locator('#header')).toHaveScreenshot('header.png');

// Compare with threshold await expect(page).toHaveScreenshot('page.png', { threshold: 0.2 });

// Compare with mask await expect(page).toHaveScreenshot('page.png', { mask: [page.locator('.dynamic-content')] });

// Update screenshots // npx playwright test --update-snapshots }); ```에 대하여

네트워크 Interception

자주 묻는 질문

```javascript test('request interception', async ({ page }) => { // Intercept all requests await page.route('**/*', route => { console.log('Request:', route.request().url()); route.continue(); });

// Intercept specific requests await page.route('**/api/users', route => { // Block request route.abort();

// Modify request
route.continue({
  headers: {
    ...route.request().headers(),
    'Authorization': 'Bearer token'
  }
});

// Mock response
route.fulfill({
  status: 200,
  contentType: 'application/json',
  body: JSON.stringify({ users: [] })
});

});

await page.goto('https://example.com'); }); ```의 경우

응답 Mocking

카지노사이트

네트워크 모니터링

카지노사이트

인증현황

기본 인증

카지노사이트

세션 관리

카지노사이트

OAuth 및 토큰 인증

카지노사이트

멀티 팩터 인증

카지노사이트

모바일 테스트

장치 Emulation

```javascript import { test, devices } from '@playwright/test';

test('mobile testing', async ({ browser }) => { // iPhone 12 const iPhone = devices['iPhone 12']; const context = await browser.newContext({ ...iPhone }); const page = await context.newPage();

await page.goto('https://example.com');

// Test mobile-specific features await expect(page.locator('.mobile-menu')).toBeVisible(); await expect(page.locator('.desktop-menu')).toBeHidden();

await context.close(); });

// Using project configuration test.describe('Mobile Tests', () => { test.use({ ...devices['iPhone 12'] });

test('mobile navigation', async ({ page }) => { await page.goto('https://example.com');

// Test hamburger menu
await page.click('.hamburger-menu');
await expect(page.locator('.mobile-nav')).toBeVisible();

}); }); ```의 경우

접촉 Interactions

```javascript test('touch interactions', async ({ page }) => { // Set mobile viewport await page.setViewportSize({ width: 375, height: 667 }); await page.goto('https://example.com');

// Tap (equivalent to click on mobile) await page.tap('#button');

// Long press await page.touchscreen.tap(100, 100, { duration: 1000 });

// Swipe await page.touchscreen.tap(100, 300); await page.mouse.move(300, 300); await page.mouse.up();

// Pinch to zoom await page.touchscreen.tap(200, 200); await page.touchscreen.tap(250, 250);

// Scroll await page.mouse.wheel(0, 100);

// Test responsive design const isMobileMenuVisible = await page.isVisible('.mobile-menu'); expect(isMobileMenuVisible).toBe(true); }); ```의 경우

Geolocation 테스트

카지노사이트

테스트 프레임

시험기관

```javascript import { test, expect } from '@playwright/test';

// Test suite test.describe('User Authentication', () => { test.beforeAll(async () => { // Setup before all tests in this describe block console.log('Setting up test data'); });

test.beforeEach(async ({ page }) => { // Setup before each test await page.goto('https://example.com/login'); });

test.afterEach(async ({ page }) => { // Cleanup after each test await page.evaluate(() => localStorage.clear()); });

test.afterAll(async () => { // Cleanup after all tests console.log('Cleaning up test data'); });

test('should login with valid credentials', async ({ page }) => { await page.fill('#username', 'testuser'); await page.fill('#password', 'password123'); await page.click('#login');

await expect(page).toHaveURL(/dashboard/);

});

test('should show error for invalid credentials', async ({ page }) => { await page.fill('#username', 'invalid'); await page.fill('#password', 'wrong'); await page.click('#login');

await expect(page.locator('.error')).toBeVisible();

}); }); ```의 경우

모수 시험

```javascript const testData = [ { username: 'user1', password: 'pass1', expected: 'dashboard' }, { username: 'user2', password: 'pass2', expected: 'admin' }, { username: 'user3', password: 'pass3', expected: 'profile' } ];

testData.forEach(({ username, password, expected }) => { test(login with ${username}, async ({ page }) => { await page.goto('https://example.com/login'); await page.fill('#username', username); await page.fill('#password', password); await page.click('#login');

await expect(page).toHaveURL(new RegExp(expected));

}); });

// Or using test.describe.parallel for parallel execution test.describe.parallel('Parallel Tests', () => { ['chrome', 'firefox', 'safari'].forEach(browser => { test(test on ${browser}, async ({ page }) => { // Test logic here }); }); }); ```를 호출합니다.

공급 업체

```javascript // fixtures.js import { test as base } from '@playwright/test';

// Custom fixture for authenticated user const test = base.extend({ authenticatedPage: async ({ page }, use) => { // Login before each test await page.goto('https://example.com/login'); await page.fill('#username', 'testuser'); await page.fill('#password', 'password123'); await page.click('#login'); await page.waitForURL('**/dashboard');

await use(page);

// Logout after each test
await page.click('#logout');

} });

// Use custom fixture test('dashboard test', async ({ authenticatedPage }) => { await expect(authenticatedPage.locator('.welcome')).toBeVisible(); });

export { test }; ```의 경우

시험 표기

```javascript test('slow test', async ({ page }) => { test.slow(); // Mark test as slow (3x timeout)

await page.goto('https://example.com'); // Long-running test logic });

test('flaky test', async ({ page }) => { test.fixme(); // Mark test as broken

await page.goto('https://example.com'); // Flaky test logic });

test('skip on mobile', async ({ page, isMobile }) => { test.skip(isMobile, 'Not supported on mobile');

await page.goto('https://example.com'); // Desktop-only test logic });

test('conditional test', async ({ page, browserName }) => { test.skip(browserName === 'webkit', 'Not supported in Safari');

await page.goto('https://example.com'); // Browser-specific test logic }); ```로

관련 링크

Debug 모드

카지노사이트

코드에 Debugging

오프화이트

Trace 뷰어

카지노사이트

비밀번호

__CODE_BLOCK_49_로그

오류 처리

카지노사이트

성능시험

성능 미터

```javascript test('performance metrics', async ({ page }) => { await page.goto('https://example.com');

// Get performance metrics const metrics = await page.evaluate(() => { const navigation = performance.getEntriesByType('navigation')[0]; return { domContentLoaded: navigation.domContentLoadedEventEnd - navigation.domContentLoadedEventStart, loadComplete: navigation.loadEventEnd - navigation.loadEventStart, firstPaint: performance.getEntriesByName('first-paint')[0]?.startTime, firstContentfulPaint: performance.getEntriesByName('first-contentful-paint')[0]?.startTime }; });

console.log('Performance metrics:', metrics);

// Assert performance thresholds expect(metrics.domContentLoaded).toBeLessThan(2000); expect(metrics.loadComplete).toBeLessThan(5000); }); ```를 호출합니다.

Lighthouse 통합

```javascript import { playAudit } from 'playwright-lighthouse';

test('lighthouse audit', async ({ page }) => { await page.goto('https://example.com');

await playAudit({ page, thresholds: { performance: 90, accessibility: 90, 'best-practices': 90, seo: 90, }, port: 9222, }); }); ```의 경우

네트워크 성능

카지노사이트

API 테스트

REST API 테스트

카지노사이트

API 인증

```javascript test('API with authentication', async ({ request }) => { // Login to get token const loginResponse = await request.post('https://api.example.com/auth/login', { data: { username: 'testuser', password: 'password123' } });

const { token } = await loginResponse.json();

// Use token for authenticated requests const response = await request.get('https://api.example.com/protected', { headers: { 'Authorization': Bearer ${token} } });

expect(response.status()).toBe(200); }); ```로

GraphQL 테스트

카지노사이트

연락처

Visual Regression 테스트

카지노사이트

구성 요소 비주얼 테스트

카지노사이트

Cross-browser 시각 테스트

``javascript ['chromium', 'firefox', 'webkit'].forEach(browserName => { test(visual test on ${browserName}`, async ({ page }) => { await page.goto('https://example.com');

await expect(page).toHaveScreenshot(`homepage-${browserName}.png`);

}); }); ```에

CI/CD 통합

GitHub 작업

```yaml

.github/workflows/playwright.yml

name: Playwright Tests on: push: branches: [ main, master ] pull_request: branches: [ main, master ] jobs: test: timeout-minutes: 60 runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: 18 - name: Install dependencies run: npm ci - name: Install Playwright Browsers run: npx playwright install --with-deps - name: Run Playwright tests run: npx playwright test - uses: actions/upload-artifact@v3 if: always() with: name: playwright-report path: playwright-report/ retention-days: 30 ```의 경우

Docker 통합

카지노사이트

카지노사이트

Jenkins 파이프 라인

```groovy pipeline { agent any

stages {
    stage('Install Dependencies') {
        steps {
            sh 'npm ci'
            sh 'npx playwright install --with-deps'
        }
    }

    stage('Run Tests') {
        steps {
            sh 'npx playwright test'
        }
        post {
            always {
                publishHTML([
                    allowMissing: false,
                    alwaysLinkToLastBuild: false,
                    keepAll: true,
                    reportDir: 'playwright-report',
                    reportFiles: 'index.html',
                    reportName: 'Playwright Report'
                ])
            }
        }
    }
}

} ```의 경우

고급 기능

주문 일치

카지노사이트

페이지 개체 모델

카지노사이트

글로벌 설정 및 Teardown

카지노사이트

최고의 연습

시험기관

카지노사이트

신뢰할 수있는 선택자

카지노사이트

오류 처리

카지노사이트

성과 모범 사례

  • Auto-waiting 사용: 자동으로 요소를 기다립니다
  • ** 불필요한 대기 **: 필요한 경우 page.waitForTimeout()를 사용하지 마십시오.
  • ** 브라우저 컨텍스트 사용 **: 가능한 한 테스트 사이의 맥락
  • 시험: 사용 fullyParallel: true 구성
  • ** 최적화 선택자 **: data-testid와 같은 효율적인 selectors 사용

유지 보수 모범 사례

  • **Keep 테스트 독립 **: 각 시험은 고립에서 실행할 수 있어야 합니다
  • ** 페이지 개체 모델 사용 **: 재사용 가능한 클래스의 페이지 상호 작용을 캡슐화
  • ** 정확한 정리 **: 시험 사이 명확한 국가
  • ** 의미있는 테스트 이름 사용 **: 테스트가 확인되는지 설명합니다.
  • Regular 업데이트: Playwright 및 브라우저 업데이트 유지

제품정보

Playwright는 강력한 현대 웹 테스트 프레임 워크입니다.

  • **Cross-browser 지원 **: 크롬, Firefox 및 WebKit에 대한 테스트
  • Auto-waiting: 요소에 대한 지능형 대기
  • Powerful Selectors: 역할 기반을 포함한 여러 선택기 전략
  • 네트워크 연동: Mock 및 모니터 네트워크 요청
  • Mobile Testing: 장치 에뮬레이션 및 터치 상호 작용
  • Visual Testing: 스크린 샷 비교 및 시각 회귀 테스트
  • ** 디버깅 도구**: Trace viewer, 디버그 모드 및 개발자 도구 통합
  • CI/CD 준비: 대중적인 CI/CD 플랫폼과 쉬운 통합
  • ** API Testing**: REST 및 GraphQL API 테스트를 위한 내장 지원
  • Performance Testing: 내장 성능 측정 및 Lighthouse 통합

Playwright의 현대적인 아키텍처와 포괄적인 기능은 최종 테스트, 브라우저 자동화 및 웹 스크랩 작업을 위한 훌륭한 선택입니다.

<문서> 기능 copyToClipboard () 이름 * const 명령어 = document.querySelectorAll('code'); let allCommands = ''; 명령. forEach(cmd =>의 경우 모든Commands +=cmd.textContent + navigator.clipboard.write텍스(allCommands); alert('모든 명령은 클립보드에 복사!'); 이름 *

함수 생성PDF() { 창. 인쇄 (); 이름 *