Playwright Testing Setup
Overview
This document describes the Playwright testing setup for the Momentum Learning Management Platform. All tests must pass before merging feature branches to the main branch.
Test Structure
Test Files Location
All Playwright tests are located in /tests/e2e/ directory:
- home.spec.ts - Tests for the home page (landing page)
- courses.spec.ts - Tests for the courses catalog page
- course-detail.spec.ts - Tests for individual course detail pages
- lesson-detail.spec.ts - Tests for lesson pages
- dashboard.spec.ts - Tests for the user dashboard
- navigation.spec.ts - Tests for navigation and routing between pages
- example.spec.ts - Original example test (can be removed)
Test Coverage
Home Page Tests (38 tests)
- Header and navigation rendering
- Hero section and CTAs
- Feature cards
- Course preview section
- Footer links
- Responsive layouts (mobile, tablet, desktop)
Courses Page Tests (25 tests)
- Search functionality
- Category filtering
- Duration filtering
- Combined filters
- Course grid display
- Empty states
- Filter panel toggle
- Responsive layouts
Course Detail Page Tests (28 tests)
- Course information display
- Tab navigation (Overview/Curriculum)
- Instructor information
- What you’ll learn section
- Curriculum display
- Lesson locking/unlocking
- Navigation to lessons
- Responsive layouts
Lesson Detail Page Tests (30+ tests)
- Video player
- Lesson content display
- Action items checkboxes
- Progress tracking
- Mark as complete functionality
- Key takeaways
- Resources section
- Lesson navigation (previous/next)
- Responsive layouts
Dashboard Tests (35+ tests)
- User greeting and stats
- Active courses display
- Progress bars
- Continue learning functionality
- Achievements display
- Daily goals
- Upcoming lessons
- Learning stats
- Responsive layouts
Navigation Tests (20+ tests)
- Navigation between all pages
- Header consistency
- Deep linking
- Browser back/forward
- Active link highlighting
- Error handling
Total: 170+ comprehensive test cases
Running Tests
Local Development
# Install dependencies (if not already done)
npm install
# Run all tests
npx playwright test
# Run tests in headed mode (see browser)
npx playwright test --headed
# Run tests in UI mode (interactive)
npx playwright test --ui
# Run specific test file
npx playwright test tests/e2e/courses.spec.ts
# Run tests with specific tag
npx playwright test --grep @smoke
# Run tests in a specific browser
npx playwright test --project=chromium
npx playwright test --project=firefox
npx playwright test --project=webkit
# Debug tests
npx playwright test --debug
View Test Reports
# Open HTML report
npx playwright show-report
# Report is automatically generated in playwright-report/ directory
CI/CD Integration
GitHub Actions Workflow
The Playwright tests run automatically on:
- Push to main/master branches
- Pull Request events: opened, synchronize, reopened
Workflow Features
- Automatic Test Execution: Tests run on every PR and push
- Test Result Comments: Automated comments on PRs with test results
- Artifact Upload: Test reports and results are uploaded as artifacts
- Multiple Browsers: Tests run on Chromium, Firefox, and WebKit
- Retries: Tests retry up to 2 times on failure in CI
- Screenshots & Videos: Captured on test failures
Making Playwright Tests Required
To make Playwright tests a required check before merging to main:
Option 1: GitHub Branch Protection Rules (Recommended)
- Go to your GitHub repository
- Navigate to Settings → Branches
- Under “Branch protection rules”, click Add rule or edit existing rule for
main - Configure the following settings:
- Branch name pattern:
main - ✅ Require status checks to pass before merging
- ✅ Require branches to be up to date before merging
- In the status checks search box, type:
test(this is the job name from workflow) - Select test from the list
- ✅ Do not allow bypassing the above settings
- Branch name pattern:
- Click Create or Save changes
Option 2: Using Rulesets (GitHub Enterprise)
- Go to Settings → Rules → Rulesets
- Click New ruleset → New branch ruleset
- Name:
Main Branch Protection - Target branches:
main - Add rule: Require status checks to pass
- Add status check:
test - Click Create
PR Comment Format
The workflow automatically posts comments on PRs with the following format:
## ✅ Playwright Test Results
### Test Summary
| Status | Count |
|--------|-------|
| ✅ Passed | 150 |
| ❌ Failed | 0 |
| ⏭️ Skipped | 0 |
| 📊 Total | 150 |
### Details
- **Status**: ✅ All tests passed!
- **Branch**: `feature/my-feature`
- **Commit**: abc123def
- **Run**: [View full report](link)
---
*Playwright tests are required to pass before merging to main.*
Configuration
playwright.config.ts
Key configuration settings:
{
testDir: './tests/e2e',
fullyParallel: true,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
// CI-specific reporters
reporter: process.env.CI
? [['html'], ['json'], ['github'], ['list']]
: [['html'], ['list']],
// Base URL
use: {
baseURL: 'http://localhost:3000',
screenshot: 'only-on-failure',
video: 'retain-on-failure',
trace: 'on-first-retry',
},
// Auto-start dev server
webServer: {
command: 'cd frontend && npm run dev',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
timeout: 120000,
},
}
Writing New Tests
Test Structure Template
import { test, expect } from '@playwright/test';
test.describe('Feature Name', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/your-page');
});
test('should do something specific', async ({ page }) => {
// Arrange
const element = page.getByRole('button', { name: 'Click me' });
// Act
await element.click();
// Assert
await expect(page).toHaveURL(/expected-url/);
});
test('should be responsive on mobile', async ({ page }) => {
await page.setViewportSize({ width: 375, height: 667 });
await expect(page.getByRole('heading')).toBeVisible();
});
});
Best Practices
- Use Semantic Locators: Prefer
getByRole,getByLabel,getByTextover CSS selectors - Test User Journeys: Focus on what users actually do
- Keep Tests Independent: Each test should run in isolation
- Use Descriptive Names: Test names should clearly describe what they’re testing
- Test Responsiveness: Include mobile, tablet, and desktop viewport tests
- Handle Async Operations: Use proper
awaitand timeout settings - Clean Up After Tests: Use
afterEachfor cleanup if needed - Use Page Object Model: For complex pages, consider creating page objects
Example: Testing a Form
test('should submit contact form successfully', async ({ page }) => {
await page.goto('/contact');
// Fill form
await page.getByLabel('Name').fill('John Doe');
await page.getByLabel('Email').fill('john@example.com');
await page.getByLabel('Message').fill('Test message');
// Submit
await page.getByRole('button', { name: 'Submit' }).click();
// Verify success
await expect(page.getByText('Message sent successfully')).toBeVisible();
});
Debugging Failed Tests
Local Debugging
# Run with headed browser to see what's happening
npx playwright test --headed
# Run with debug mode (step through tests)
npx playwright test --debug
# Open trace viewer for failed test
npx playwright show-trace trace.zip
CI Debugging
- Check GitHub Actions logs: View detailed logs in the Actions tab
- Download artifacts: Download test reports and screenshots from the workflow run
- View screenshots: Failed tests capture screenshots automatically
- Watch videos: Videos are recorded for failed tests
- Check trace files: Trace files show step-by-step execution
Troubleshooting
Common Issues
Tests fail locally but pass in CI
- Ensure your dev server is running
- Check for timing issues (add appropriate waits)
- Verify environment variables
Tests are flaky
- Add explicit waits for dynamic content
- Increase timeout values if needed
- Check for race conditions
WebServer timeout
- Increase
webServer.timeoutin config - Check if frontend builds successfully
- Verify no port conflicts
Screenshots not captured
- Ensure
screenshot: 'only-on-failure'is in config - Check file permissions
- Verify output directory exists
Maintenance
Regular Tasks
- Update Playwright: Keep Playwright updated for latest features and fixes
npm install -D @playwright/test@latest npx playwright install -
Review Flaky Tests: Monitor test stability and fix flaky tests
-
Update Selectors: When UI changes, update test selectors
-
Add New Tests: For new features, add corresponding tests
- Clean Up Old Tests: Remove obsolete tests when features are deprecated
Resources
- Playwright Documentation
- Playwright Best Practices
- Playwright API Reference
- GitHub Actions Documentation
Support
For issues or questions:
- Check the Playwright documentation
- Review existing test examples
- Check GitHub Actions logs for CI failures
- Contact the development team
Last Updated: 2025-11-14 Playwright Version: 1.56.1 Node Version: LTS