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 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

  1. Automatic Test Execution: Tests run on every PR and push
  2. Test Result Comments: Automated comments on PRs with test results
  3. Artifact Upload: Test reports and results are uploaded as artifacts
  4. Multiple Browsers: Tests run on Chromium, Firefox, and WebKit
  5. Retries: Tests retry up to 2 times on failure in CI
  6. Screenshots & Videos: Captured on test failures

Making Playwright Tests Required

To make Playwright tests a required check before merging to main:

  1. Go to your GitHub repository
  2. Navigate to SettingsBranches
  3. Under “Branch protection rules”, click Add rule or edit existing rule for main
  4. 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
  5. Click Create or Save changes

Option 2: Using Rulesets (GitHub Enterprise)

  1. Go to SettingsRulesRulesets
  2. Click New rulesetNew branch ruleset
  3. Name: Main Branch Protection
  4. Target branches: main
  5. Add rule: Require status checks to pass
  6. Add status check: test
  7. 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

  1. Use Semantic Locators: Prefer getByRole, getByLabel, getByText over CSS selectors
  2. Test User Journeys: Focus on what users actually do
  3. Keep Tests Independent: Each test should run in isolation
  4. Use Descriptive Names: Test names should clearly describe what they’re testing
  5. Test Responsiveness: Include mobile, tablet, and desktop viewport tests
  6. Handle Async Operations: Use proper await and timeout settings
  7. Clean Up After Tests: Use afterEach for cleanup if needed
  8. 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

  1. Check GitHub Actions logs: View detailed logs in the Actions tab
  2. Download artifacts: Download test reports and screenshots from the workflow run
  3. View screenshots: Failed tests capture screenshots automatically
  4. Watch videos: Videos are recorded for failed tests
  5. 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.timeout in 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

  1. Update Playwright: Keep Playwright updated for latest features and fixes
    npm install -D @playwright/test@latest
    npx playwright install
    
  2. Review Flaky Tests: Monitor test stability and fix flaky tests

  3. Update Selectors: When UI changes, update test selectors

  4. Add New Tests: For new features, add corresponding tests

  5. Clean Up Old Tests: Remove obsolete tests when features are deprecated

Resources

Support

For issues or questions:

  1. Check the Playwright documentation
  2. Review existing test examples
  3. Check GitHub Actions logs for CI failures
  4. Contact the development team

Last Updated: 2025-11-14 Playwright Version: 1.56.1 Node Version: LTS


Back to top

Momentum LMS © 2025. Distributed under the MIT license.