0Pricing
Next.js 15 Fullstack Web Apps · Урок

Сквозное тестирование с Playwright

Настройте сквозные тесты для моделирования взаимодействия пользователя во всём сценарии работы приложения.

«Сквозное тестирование с Playwright» — бесплатный урок Next.js 15 Fullstack Web Apps на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Next.js 15 Fullstack Web Apps, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Next.js 15 Fullstack Web Apps содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

What is End-to-End Testing?

End-to-End (E2E) testing simulates a real user's journey through your application, from start to finish. It tests the entire stack: frontend, backend, and database.

Think of it as a robot user interacting with your app in a browser. This ensures all parts of your system work together as expected, catching issues that unit or integration tests might miss.

Why Playwright for E2E?

Playwright is a powerful open-source tool by Microsoft designed for reliable E2E testing. It offers several key advantages:

  • Cross-browser: Tests Chromium, Firefox, and WebKit (Safari).
  • Auto-wait: Automatically waits for elements to be ready, reducing flakiness.
  • Robust actions: Simulates real user interactions like clicks, fills, and key presses.
  • Fast & parallel: Can run tests across multiple browsers simultaneously.

Setting Up Playwright

To get started, you'll need to install Playwright in your Next.js project. This command sets up Playwright and downloads necessary browser binaries:

npm init playwright@latest

This will guide you through setting up a basic configuration file (playwright.config.ts) and an example test. Remember to have your Next.js application running (e.g., npm run dev) when running E2E tests!

Your First Playwright Test

Let's write a simple test to navigate to a page and check its title. Playwright tests are typically written in JavaScript or TypeScript.

This example assumes your Next.js app is running on http://localhost:3000.

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

test('homepage has expected title', async ({ page }) => {
  await page.goto('http://localhost:3000/');
  // Check if the page title contains 'Next.js App'
  await expect(page).toHaveTitle(/Next.js App/);
});

Interacting with Elements

Playwright provides powerful locators to find elements on the page. You can interact with these elements by filling input fields, clicking buttons, and more.

Common locators include getByRole(), getByText(), getByLabel(), and locator() for CSS selectors.

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

test('fill and submit a contact form', async ({ page }) => {
  await page.goto('http://localhost:3000/contact');

  // Fill input fields by label or placeholder
  await page.getByLabel('Your Name').fill('Alice');
  await page.getByPlaceholder('email@example.com').fill('alice@example.com');

  // Click the submit button
  await page.getByRole('button', { name: 'Send Message' }).click();

  // Assert that a success message appears
  await expect(page.getByText('Message sent successfully!')).toBeVisible();
});

Assertions and Auto-Waiting

Playwright's expect API is used to make assertions about the state of your application. A key feature is auto-waiting, where Playwright automatically waits for elements to become visible, enabled, or stable before performing an action or assertion.

This significantly reduces the need for manual waits, making your tests more robust and less prone to flakiness.

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

test('check item count', async ({ page }) => {
  await page.goto('http://localhost:3000/products');

  // Playwright waits for the list to render
  const productList = page.locator('.product-item');
  await expect(productList).toHaveCount(5);

  // Click a filter button
  await page.getByRole('button', { name: 'Filter by Category A' }).click();

  // Playwright waits for the list to update after filtering
  await expect(productList).toHaveCount(2);
});

Testing a Full User Flow

Let's simulate a more complex user journey: a user logging in, navigating to a dashboard, and verifying content. This demonstrates how E2E tests cover multiple pages and interactions.

Ensure your Next.js application has a login page and a dashboard for this test to pass.

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

test('user can log in and view dashboard', async ({ page }) => {
  await page.goto('http://localhost:3000/login');

  // Fill login form
  await page.getByLabel('Username').fill('testuser');
  await page.getByLabel('Password').fill('securepassword');
  await page.getByRole('button', { name: 'Log In' }).click();

  // Wait for navigation to the dashboard and verify content
  await page.waitForURL('http://localhost:3000/dashboard');
  await expect(page.getByRole('heading', { name: 'Welcome, testuser!' })).toBeVisible();
  await expect(page.getByText('Your recent activity')).toBeVisible();
});

Running Tests & Reporting

After writing your tests, you can run them from your terminal. Playwright provides a powerful test runner and various reporting options:

  • Run all tests: npx playwright test
  • Run specific test file: npx playwright test example.spec.js
  • Run tests in headed mode (browser visible): npx playwright test --headed
  • HTML Reporter: After tests run, open playwright-report/index.html for a detailed, interactive report.

Best Practices for E2E Tests

To write effective and maintainable E2E tests:

  • Target user-facing elements: Use locators that reflect how a user sees the page (e.g., getByRole, getByText).
  • Use data-testid attributes: For elements without clear text or roles, add data-testid attributes for robust selection.
  • Keep tests independent: Each test should set up its own state and not rely on previous tests.
  • Balance test types: E2E tests are slower; use them for critical user flows, and rely on unit/integration tests for smaller components.

Playwright Test Concepts

Which of the following are key benefits or features of Playwright for End-to-End testing?

Recap: E2E with Playwright

We've explored End-to-End testing and how Playwright helps you simulate real user interactions across your entire Next.js application.

You learned to set up Playwright, write tests that navigate, interact with elements, and assert outcomes. With its auto-waiting capabilities and cross-browser support, Playwright is a powerful tool for ensuring the reliability of your fullstack applications.

Часто задаваемые вопросы

Урок «Сквозное тестирование с Playwright» бесплатный?

Да — полный текст урока «Сквозное тестирование с Playwright» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Next.js 15 Fullstack Web Apps, подпишись на CoddyKit PRO. Курс Next.js 15 Fullstack Web Apps содержит 4 уроков всего.

Чему я научусь в уроке «Сквозное тестирование с Playwright»?

Настройте сквозные тесты для моделирования взаимодействия пользователя во всём сценарии работы приложения. Ты практикуешь Next.js 15 Fullstack Web Apps с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Next.js 15 Fullstack Web Apps?

Предыдущий опыт не требуется. Next.js 15 Fullstack Web Apps на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Сквозное тестирование с Playwright»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Next.js 15 Fullstack Web Apps?

Да. Каждый урок Next.js 15 Fullstack Web Apps включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Модульное и интеграционное тестирование
  2. Сквозное тестирование с Playwright
  3. Монорепозитории и микрофронтенды
  4. Имитация и тестирование серверных компонентов
← Назад к Next.js 15 Fullstack Web Apps