Перейти к содержимому

18. Playwright: введение

Playwright

Playwright — E2E тест-фреймворк от Microsoft. Поддерживает Chromium, Firefox, WebKit. Быстрее Cypress, лучшая поддержка async.

Окно терминала
npm install --save-dev @playwright/test
# Скачать браузеры
npx playwright install
# Или с инициализацией проекта
npm init playwright@latest
playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests/e2e',
timeout: 30000,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
// Базовый URL
use: {
baseURL: 'http://localhost:3000',
screenshot: 'only-on-failure',
video: 'retain-on-failure',
trace: 'on-first-retry',
},
// Тестируемые браузеры
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'firefox', use: { ...devices['Desktop Firefox'] } },
{ name: 'webkit', use: { ...devices['Desktop Safari'] } },
{ name: 'Mobile Chrome', use: { ...devices['Pixel 5'] } },
],
// Запустить dev server перед тестами
webServer: {
command: 'npm run dev',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
},
});
tests/e2e/home.spec.ts
import { test, expect } from '@playwright/test';
test('homepage has title', async ({ page }) => {
await page.goto('/');
await expect(page).toHaveTitle(/My App/);
await expect(page.locator('h1')).toBeVisible();
});
test('navigation works', async ({ page }) => {
await page.goto('/');
await page.click('text=About');
await expect(page).toHaveURL('/about');
await expect(page.locator('h1')).toContainText('About');
});
tests/pages/LoginPage.ts
import { Page, Locator, expect } from '@playwright/test';
export class LoginPage {
readonly page: Page;
readonly emailInput: Locator;
readonly passwordInput: Locator;
readonly submitButton: Locator;
readonly errorMessage: Locator;
constructor(page: Page) {
this.page = page;
this.emailInput = page.getByLabel('Email');
this.passwordInput = page.getByLabel('Password');
this.submitButton = page.getByRole('button', { name: /login/i });
this.errorMessage = page.getByRole('alert');
}
async goto() {
await this.page.goto('/login');
}
async login(email: string, password: string) {
await this.emailInput.fill(email);
await this.passwordInput.fill(password);
await this.submitButton.click();
}
async expectError(message: string) {
await expect(this.errorMessage).toContainText(message);
}
}
// tests/e2e/auth.spec.ts
import { test, expect } from '@playwright/test';
import { LoginPage } from '../pages/LoginPage';
test('successful login', async ({ page }) => {
const loginPage = new LoginPage(page);
await loginPage.goto();
await loginPage.login('[email protected]', 'password123');
await expect(page).toHaveURL('/dashboard');
});
test('shows error for wrong credentials', async ({ page }) => {
const loginPage = new LoginPage(page);
await loginPage.goto();
await loginPage.login('[email protected]', 'wrongpassword');
await loginPage.expectError('Invalid credentials');
await expect(page).toHaveURL('/login'); // остались на странице
});
Окно терминала
# Запустить все E2E тесты
npx playwright test
# Один файл
npx playwright test auth.spec.ts
# Один тест
npx playwright test -g "successful login"
# С UI (интерактивный режим)
npx playwright test --ui
# Показать браузер
npx playwright test --headed
# Debug mode (пошаговое выполнение)
npx playwright test --debug
# Отчёт
npx playwright show-report
// Остановить выполнение для отладки
await page.pause();
// Запись теста (кодогенерация)
// npx playwright codegen http://localhost:3000
  1. Установи Playwright, настрой playwright.config.ts
  2. Напиши E2E тест для страницы регистрации
  3. Создай Page Object для главной страницы
  • Playwright — мощный E2E фреймворк (Chromium + Firefox + Safari)
  • Page Object Model — организация кода тестов
  • —ui — интерактивный режим отладки
  • codegen — автогенерация тестов по действиям в браузере