Modern End-to-End Testing with Playwright
Master reliable end-to-end testing with Playwright using a real-world e-commerce application. Learn best practices for UI testing, API testing, visual regression, and building maintainable test suites that scale with your application.
Complete Tutorial Project
Follow along with a fully functional Next.js e-commerce application called TestShop. Includes comprehensive test suites covering all major Playwright features and testing patterns.
View on GitHubIntroduction
End-to-end testing has evolved significantly in recent years, and Playwright has emerged as the leading solution for modern web applications. Developed by Microsoft, Playwright provides a unified API for testing across Chromium, Firefox, and WebKit browsers, offering unparalleled reliability and speed for automated testing.
This comprehensive tutorial guides you through building a complete testing strategy using Playwright with a real-world e-commerce application called TestShop. You'll learn not just the technical aspects of writing tests, but also best practices for maintaining reliable test suites that scale with your application.
What is Playwright?
Playwright is a Node.js library that provides a high-level API to control browsers programmatically. Unlike traditional testing tools, Playwright offers true cross-browser testing with consistent behavior across different browser engines, making it ideal for comprehensive end-to-end testing.
Traditional Testing
• Single browser support• Flaky test results• Limited mobile testingInconsistent results across environments
Playwright Testing
// Cross-browser testing
await test.step('Test in all browsers', async () => {
// Runs in Chromium, Firefox, WebKit
await page.goto('/products');
await expect(page).toHaveTitle('TestShop');
});Reliable testing across all modern browsers
Core Playwright Concepts
Locator Strategies
Playwright's locator system is designed for reliability and maintainability. Unlike traditional selectors that break easily, Playwright locators are resilient to DOM changes and provide clear, semantic ways to find elements.
// Test ID locators (most reliable)
await page.getByTestId('login-button').click();
// Role-based locators (semantic)
await page.getByRole('button', { name: 'Add to Cart' }).click();
await page.getByRole('textbox', { name: 'Email Address' }).fill('user@example.com');
// Text content locators
await page.getByText('Welcome to TestShop').waitFor();
// Label-based locators (forms)
await page.getByLabel('Password').fill('secretpassword');
// Placeholder locators
await page.getByPlaceholder('Search products...').fill('laptop');Assertions and Expectations
Playwright's assertion system provides powerful, auto-retrying expectations that wait for conditions to be met, eliminating flaky tests caused by timing issues.
// Element visibility and state
await expect(page.getByTestId('product-grid')).toBeVisible();
await expect(page.getByTestId('loading-spinner')).toBeHidden();
// Text content assertions
await expect(page.getByTestId('cart-count')).toContainText('3');
await expect(page.getByRole('heading')).toHaveText('TestShop Products');
// Form value assertions
await expect(page.getByLabel('Email')).toHaveValue('user@example.com');
await expect(page.getByTestId('price-filter')).toHaveValue('100');
// URL and navigation
await expect(page).toHaveURL('/products?category=electronics');
await expect(page).toHaveTitle(/TestShop.*Products/);Visual Testing
Visual regression testing catches UI changes that functional tests might miss. Playwright's screenshot comparison is pixel-perfect and handles cross-platform differences automatically.
// Full page screenshots
await expect(page).toHaveScreenshot('homepage.png');
// Element screenshots
await expect(page.getByTestId('product-card')).toHaveScreenshot('product-card.png');
// Mobile viewport testing
await page.setViewportSize({ width: 375, height: 667 });
await expect(page).toHaveScreenshot('homepage-mobile.png');
// Custom screenshot options
await expect(page.getByTestId('hero-section')).toHaveScreenshot('hero.png', {
mask: [page.getByTestId('dynamic-content')],
threshold: 0.2
});API Testing and Network Mocking
Playwright excels at both direct API testing and network interception, allowing you to test your application's behavior under various network conditions and API responses.
// Direct API testing
const response = await request.get('/api/products');
expect(response.status()).toBe(200);
const products = await response.json();
expect(products).toHaveLength(12);
// Network mocking
await page.route('**/api/products', async route => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(mockProducts)
});
});
// Network failure simulation
await page.route('**/api/login', route => route.abort('failed'));
await page.getByTestId('login-form').submit();
await expect(page.getByTestId('error-message')).toBeVisible();Building TestShop: A Real-World Testing Example
TestShop is a comprehensive e-commerce application built specifically for demonstrating Playwright testing patterns. It includes all the complex interactions you'll encounter in real applications: authentication, form validation, dynamic content, and API integrations.
Application Architecture
TestShop follows modern web development practices with a focus on testability. Every interactive element includes proper test attributes, and the application is designed to demonstrate various testing scenarios.
Test Suite Structure
The TestShop test suite is organized by feature and complexity, making it easy to understand different testing patterns and gradually build your Playwright expertise.
tests/
├── example.spec.ts # Homepage and basic interactions
├── products.spec.ts # Product catalog and cart functionality
├── login.spec.ts # Form validation and UI testing
├── login.integration.spec.ts # Full authentication flow
├── api.login.spec.ts # Direct API testing
├── contact.spec.ts # Contact form testing
├── visual.spec.ts # Visual regression testing
├── api.spec.ts # Network mocking and API testing
├── auth.setup.ts # Authentication setup
└── authenticated.spec.ts # Tests requiring login stateAuthentication Testing Patterns
TestShop demonstrates sophisticated authentication testing, including session management, JWT tokens, and HTTP-only cookies. This mirrors real-world security implementations.
// Authentication setup for reuse across tests
// auth.setup.ts
import { test as setup } from '@playwright/test';
setup('authenticate', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Email').fill('demo@testshop.com');
await page.getByLabel('Password').fill('password123');
await page.getByRole('button', { name: 'Sign In' }).click();
await expect(page).toHaveURL('/dashboard');
await page.context().storageState({ path: 'auth.json' });
});
// Using authenticated state in tests
test.use({ storageState: 'auth.json' });
test('authenticated user can view orders', async ({ page }) => {
await page.goto('/orders');
await expect(page.getByTestId('orders-list')).toBeVisible();
});Advanced Testing Patterns
Mobile and Responsive Testing
TestShop includes comprehensive mobile testing patterns, demonstrating how to test responsive designs and mobile-specific interactions across different viewport sizes and device types.
Performance and Accessibility
Beyond functional testing, the tutorial covers performance monitoring and accessibility testing, ensuring your applications meet modern web standards and provide excellent user experiences.
CI/CD Integration
Learn how to integrate Playwright tests into your continuous integration pipeline, including parallel test execution, test result reporting, and artifact management for failed tests.
Key Benefits of Playwright Testing
Cross-Browser Reliability
Test across Chromium, Firefox, and WebKit with consistent behavior and reliable results.
Fast Execution
Parallel test execution and efficient browser management for rapid feedback cycles.
Visual Testing
Built-in screenshot comparison and visual regression testing capabilities.
Developer Experience
Excellent TypeScript support, debugging tools, and comprehensive documentation.
Getting Started
Ready to master end-to-end testing with Playwright? Follow these steps to get the TestShop tutorial project running on your local machine:
- 1Clone the repository:
git clone https://github.com/audoir/playwright-tutorial.git - 2Install dependencies:
npm install - 3Start the TestShop application:
npm run dev - 4Run the test suite:
npm test- Run all testsnpm run test:ui- Interactive UI modenpm run test:report- HTML report - 5Explore the application:http://localhost:3000 - TestShop applicationDemo credentials: demo@testshop.com / password123
Learning Outcomes
By completing this tutorial, you will have gained hands-on experience with:
- • Setting up Playwright with TypeScript and modern configuration
- • Writing reliable locators using best practices and semantic selectors
- • Implementing comprehensive form testing with validation scenarios
- • Building authentication flows and session management testing
- • Creating visual regression tests for UI consistency
- • API testing and network mocking for various scenarios
- • Mobile and responsive design testing across viewports
- • Debugging failed tests with trace viewer and screenshots
- • Organizing test suites for maintainability and scalability
- • Integrating Playwright into CI/CD pipelines
Conclusion
Playwright represents the future of end-to-end testing, offering developers the reliability, speed, and comprehensive features needed for modern web applications. By providing true cross-browser testing with a unified API, Playwright eliminates many of the traditional pain points in automated testing.
The TestShop tutorial demonstrates real-world testing patterns that you can immediately apply to your own projects. From basic UI interactions to complex authentication flows and visual regression testing, these patterns form the foundation for building robust, maintainable test suites.
About the Author
Wayne Cheng is the founder and AI app developer at Audoir, LLC. Prior to founding Audoir, he worked as a hardware design engineer for Silicon Valley startups and an audio engineer for creative organizations. He holds an MSEE from UC Davis and a Music Technology degree from Foothill College.
Further Exploration
To continue your Playwright journey, explore the complete tutorial repository and experiment with extending the TestShop application. Consider adding features like user reviews, wishlist functionality, or payment processing to practice advanced testing scenarios.
For more AI-powered development tools and tutorials, visit Audoir .