How to Set Up Playwright in a JavaScript Project

Related Courses

Next Batch : Invalid Date

Next Batch : Invalid Date

Next Batch : Invalid Date

How to Set Up Playwright in a JavaScript Project

1. Introduction: Why Playwright Setup Matters

In today’s agile development world, teams need speed and reliability. Automation testing ensures consistent quality while accelerating releases and Playwright stands out as one of the most advanced, developer-friendly frameworks for browser automation.

Created by Microsoft, Playwright automates real user actions like navigation, form filling, clicks, and screenshots. It supports all major browsers Chromium (Chrome/Edge), Firefox, and WebKit (Safari) with a single API.

This guide will help you set up Playwright from scratch in a JavaScript project, covering installation, test writing, configuration, CI/CD integration, and debugging everything you need to start automating confidently.

2. What Is Playwright?

Playwright is an open-source testing library that enables developers to automate browsers using JavaScript or TypeScript. It simplifies cross-browser testing and makes automation faster, more stable, and easier to maintain.

Key Features:

  • Cross-browser support: Chrome, Firefox, Safari, and Edge

  • Auto-waiting for elements to load

  • Parallel test execution

  • Network request interception and mocking

  • Headless and headed modes

  • Mobile device emulation

It integrates seamlessly with Node.js, making it perfect for modern JavaScript projects.

3. Prerequisites for Setting Up Playwright

Before installing Playwright, make sure your environment meets these requirements.

System Requirements

  • Operating System: Windows, macOS, or Linux

  • Node.js Version: 16 or higher

  • NPM: Installed automatically with Node.js

  • IDE: Visual Studio Code or any preferred editor

Verify Installation

Run the following commands in your terminal:

node -v npm -v

If both return valid versions, you’re good to proceed.

4. Creating a New JavaScript Project

Step 1: Create a Folder

mkdir playwright-setup-demo cd playwright-setup-demo

Step 2: Initialize the Project

npm init -y

This creates a package.json file that tracks dependencies and scripts.

5. Installing Playwright

Step 1: Install Playwright

npm install @playwright/test --save-dev

Step 2: Install Browser Binaries

npx playwright install

Step 3: Verify Installation

npx playwright browsers

You’ll see a list of installed browsers like Chromium, Firefox, and WebKit.

6. Setting Up Project Structure

A good structure keeps your tests clean and maintainable.

playwright-setup-demo/ │ ├── tests/ │ ├── example.spec.js │ ├── playwright.config.js ├── package.json └── README.md

Folder Breakdown:

  • tests/ - Test files

  • playwright.config.js - Global test configuration

  • package.json - Project settings and dependencies

  • README.md - Optional documentation

7. Writing Your First Playwright Test

Inside the tests folder, create example.spec.js:

const { test, expect } = require('@playwright/test');

test('Homepage has title and header text', async ({ page }) => {
  await page.goto('https://example.com');
  await expect(page).toHaveTitle(/Example Domain/);
  const header = await page.locator('h1');
  await expect(header).toHaveText('Example Domain');
});

Run the test:

npx playwright test

Playwright will launch a browser, navigate to the page, and verify the title.

8. Understanding the Test Script

Command Description
test() Defines an individual test
page Represents a browser tab
goto() Navigates to a page
expect() Asserts a condition
locator() Finds elements on the page

Playwright uses async/await syntax to handle asynchronous browser operations, eliminating timing-related errors.

9. Configuring Playwright

Generate a configuration file automatically:

npx playwright init 

Example:

// playwright.config.js
module.exports = {
  testDir: './tests',
  timeout: 30000,
  retries: 1,
  use: {
    headless: true,
    viewport: { width: 1280, height: 720 },
    screenshot: 'on',
    video: 'on-first-retry'
  },
  projects: [
    { name: 'Chromium', use: { browserName: 'chromium' } },
    { name: 'Firefox', use: { browserName: 'firefox' } },
    { name: 'WebKit', use: { browserName: 'webkit' } }
  ]
};

This configuration allows parallel testing across browsers with screenshots and videos on failure.

10. Running Tests Across Browsers

To run on specific browsers:

npx playwright test --project=chromium
npx playwright test --project=firefox
npx playwright test --project=webkit

npx playwright test --parallel

11. Running in Headed or Headless Mode

Headless (default): Faster, ideal for CI environments.
Headed: Opens the browser for visual testing.

npx playwright test --headed

12. Debugging Playwright Tests

Playwright offers several debugging options.

  • Debug Mode:

    npx playwright test --debug
  • Pause Command:

    await page.pause();
  • Trace Viewer:

    npx playwright show-trace trace.zip

13. Generating Test Reports

Playwright generates an HTML report automatically:

npx playwright show-report

You’ll get visual summaries of test results, including screenshots and logs.

14. Integrating Playwright with CI/CD

Here’s how to run Playwright tests in GitHub Actions:

name: Playwright Tests
on: [push]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v3
        with:
          node-version: '18'
      - run: npm ci
      - run: npx playwright install
      - run: npx playwright test

This ensures your tests run automatically after every push.

15. Folder Management and Naming Conventions

Organize your project for scalability:

tests/
├── smoke/
│   └── homepage.spec.js
├── regression/
│   └── login.spec.js
├── integration/
│   └── cart.spec.js
└── utils/
    └── helpers.js

Naming Tips:

  • .spec.js for test files

  • describe() for grouping

  • test() for individual cases

16. Advanced Configurations

  • Environment Variables:
    Store credentials in a .env file:

    LOGIN_URL=https://example.com/login

    Access it:

    require('dotenv').config(); await page.goto(process.env.LOGIN_URL);
  • Command-Line Options:

    npx playwright test --grep "login" npx playwright test --reporter=list
  • Reusable Fixtures:test.beforeEach(async ({ page }) => {
      await page.goto('https://example.com/login');
    });

17. Common Playwright Setup Issues

Problem Cause Solution
playwright command not found Not installed locally Use npx playwright
Browser not launching Missing binaries Run npx playwright install
Random test failure Timing issue Use auto-wait features
Config not found Wrong filename Use playwright.config.js

18. Extending Playwright

You can expand Playwright’s capabilities by integrating it with:

  • Jest or Mocha for flexible reporting

  • Allure for advanced dashboards

  • Docker for containerized runs

  • BrowserStack or LambdaTest for cloud testing

  • API testing through network interception

For additional resources, explore [Introduction to Playwright Automation with JavaScript] and [Understanding the Data Analytics Lifecycle] for related guides.

19. Best Practices for Playwright Setup

  1. Store Playwright configs in version control

  2. Use descriptive test names

  3. Keep reusable selectors in utilities

  4. Avoid hardcoded waits

  5. Categorize tests using tags

  6. Automate report generation after runs

  7. Validate CI/CD compatibility regularly

20. Real-World Example: Login Test

const { test, expect } = require('@playwright/test');

test('Valid login redirects to dashboard', async ({ page }) => {
  await page.goto('https://example.com/login');
  await page.fill('#username', 'demo');
  await page.fill('#password', 'demo123');
  await page.click('button[type="submit"]');
  await expect(page).toHaveURL(/dashboard/);
});

This verifies that valid login credentials redirect users correctly.

21. Summary

A proper Playwright setup ensures smooth automation with fewer errors and faster test runs. Once configured, it scales effortlessly from local Software testing to enterprise-grade CI/CD pipelines.

Benefits of proper setup:

  • Reliable, consistent test runs

  • Minimal flakiness

  • Easier debugging

  • Seamless integration with DevOps pipelines

Mastering Playwright setup is the first step toward building robust, modern, and scalable browser automation frameworks.