Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Hands-On Automated Testing with Playwright
  • Table Of Contents Toc
Hands-On Automated Testing with Playwright

Hands-On Automated Testing with Playwright

By : Faraz K. Kelhini, Butch Mayhew
close
close
Hands-On Automated Testing with Playwright

Hands-On Automated Testing with Playwright

By: Faraz K. Kelhini, Butch Mayhew

Overview of this book

Hands-On Automated Testing with Playwright draws from Faraz and Butch’s extensive experience to help you harness the full potential of Microsoft's Playwright framework. The book begins with a quick setup refresher, walking you through intermediate and advanced concepts such as dynamic content handling, accessibility testing, AI-generated test scripts, and parallel test execution. You'll explore real-world applications with end-to-end testing workflows for e-commerce and single-page applications. Alongside traditional topics such as accessibility, mobile, and visual regression testing, this book delves into modern trends such as CI/CD pipelines, DevOps integration, and AI-driven testing enhancements. Each chapter is packed with practical examples, expert techniques, and performance optimization tips, helping you gain a deep understanding of maintainable automation strategies. Whether you're transitioning from manual testing or expanding your automation toolbox, this Playwright book provides the skills and confidence to build future-proof testing systems in today's complex web development landscape. *Email sign-up and proof of purchase required
Table of Contents (22 chapters)
close
close
20
Other Books You May Enjoy
21
Index

Configuring test environments

In this part, we look at configuring the Node.js environment and your Integrated Development Environment (IDE) for an effective Playwright development experience.

Setting up the Node.js environment

Make sure you’re using a stable version of Node.js, ideally the LTS version, and consider using tools such as nvm to manage different Node versions, which can be helpful when working on multiple projects.

It’s also important to keep your project structure organized so everything stays clear and easy to navigate. While there isn’t one perfect way to organize a Playwright project, here’s an example layout to give you some inspiration:

my-playwright-project/
├── tests/                    
│   ├── example.spec.ts         // Test files for different scenarios
│   ├── logged-in/
│   │   ├── api.spec.ts
│   │   ├── login.setup.ts
│   │   └── ...
│   └── logged-out/
│       ├── api.spec.ts
│       ├── auth.spec.ts
│       └── ...            
│
├── src/
│   ├── pages/                    
│   │   ├── BasePage.ts       // Common page functions and elements
│   │   ├── DashboardPage.ts  // Page Object Model for the dashboard
│   │   └── ...
│   └── utils/
│       ├── apiHelper.ts      // Utility functions for API calls
│       ├── stringUtils.ts    // Additional helpers
│       └── ...                   
│
├── fixtures/                 
│   ├── testData.json         // Sample data used for tests
│   └── ...                   
│
├── auth/
│   └── credentials.json      // Holds credentials and session details
│   └── ...                   
│
├── helpers/
│   ├── list-test.ts          // Helper functions
│   └── ...                   
│
├── test-results/             // Stores test execution results
├── playwright-report/        // Directory for Playwright test reports
├── playwright.config.ts      // Playwright configuration settings
├── package.json              // NPM package manifest
├── tsconfig.json             // TypeScript configuration
├── .gitignore:               // files to exclude from version control
└── README.md                 // Project overview and documentation

Let’s dive a bit deeper:

  • Configuration lives in Root: your TS compiler options, playwright.config.ts, environment variables, plus your package.json and .gitignore. Docs and top-level scripts belong here too.
  • In tests/, we’ve grouped logged-in and logged-out scenarios into subfolders so you can share setup logic (such as login.setup.ts) and keep related specs together.
  • src/ is the heart of your Page Object Model (POM). pages/ holds individual page classes, while utils/ is home to low-level helpers and shared API logic.
  • fixtures/ holds static or semi-static test data (JSON, CSV, etc.) that your tests can load.
  • auth/ contains credentials, session dumps, tokens, or anything sensitive or environment-specific you don’t want scattered through your code.
  • helpers/ holds one-off or cross-cutting functions that don’t fit neatly in utils/, such as list generators or custom matchers.
  • Finally, auto-generated output, such as raw JSON logs, HTML reports, screenshots, and videos, is stored in test-results/ and playwright-report/.

This organization keeps your test code, helpers, and configuration clearly separated, so when the project grows, you always know where to look, and more importantly, where to add new files.

Setting up your IDE

Using a modern IDE such as Visual Studio Code (VS Code) can improve your coding experience. Start by installing helpful extensions such as the official Playwright Test extension, which provides syntax highlighting, code completion, and inline test results:

Figure 1.1: Extensions view in VS Code

Figure 1.1: Extensions view in VS Code

To install the extension in VS Code, follow these steps:

  1. Go to the Extensions view by clicking the extensions icon in the Activity Bar on the side (or press Ctrl + Shift + X).
  2. In the search bar, type Playwright Test.
  3. Find the extension by Microsoft named Playwright Test for VS Code and click Install.

You can also add ESLint and Prettier for code formatting, which help keep your code consistent. Setting them up is pretty similar to how you installed Playwright Test for VS Code.

Configuring Playwright settings

Playwright allows you to customize how your tests run by using the playwright.config.ts file. In this file, you can set global preferences, tweak browser behavior, and fine-tune how your tests are executed. This section will guide you through the key settings to help you get started.

First, go to your project directory. If you don’t have a playwright.config.ts file yet (maybe you’re working with an existing project), you can create the config file manually.

The following is an example of a minimal configuration:

import { defineConfig } from '@playwright/test';
export default defineConfig({
  testDir: './tests', // Directory where tests are located
  timeout: 30000, // Test timeout in milliseconds
  use: {
    browserName: 'chromium', // Default browser
    headless: true, // Run tests in headless mode
    viewport: { width: 1280, height: 720 }, // Default viewport size
  },
});

Once the initial configuration is in place, you can begin customizing it to better suit your project’s specific testing needs.

The configuration file supports a variety of options to customize test execution. When you’re setting things up, it’s best to keep it simple at first. Start with the basic settings, and only add complexity if you need it later. Also, make sure to document your choices by adding comments in the config file. This way, you can easily remember why certain settings were made, and it’ll be clearer for anyone else who works on it later.

The following are the most commonly used settings. We’ll come back to many of these in later chapters, so no worries if you’re not totally sure how they work just yet.

Test directory and file matching

Use these options to control which files Playwright includes or excludes when discovering tests:

  • testDir: Specifies the directory containing your test files. By default, Playwright looks for tests in the ./tests folder.
  • testMatch: Defines a pattern to match test files (such as *.spec.ts or /*.test.ts).
  • testIgnore: Excludes files or directories from test discovery (such as /*.setup.ts).

The following is an example:

export default defineConfig({
  testDir: './tests',
  testMatch: '/*.spec.ts',
  testIgnore: '/*.unit.ts',
});

Timeouts

These settings define how long Playwright should wait before timing out at different stages of the test run:

  • timeout: Maximum time (in milliseconds) for a test to complete
  • globalTimeout: Maximum time for the entire test suite to run
  • actionTimeout: Timeout for individual Playwright actions (such as page.click())

The following is an example:

export default defineConfig({
  timeout: 30000, // 30 seconds per test
  globalTimeout: 1800000, // 30 minutes for the entire suite
  use: {
    actionTimeout: 10000, // 10 seconds per action
  },
});

Browser and context options

The use property defines default browser and context settings for all tests:

  • browserName: Specifies the browser (Chromium, Firefox, or WebKit)
  • headless: Runs browsers in headless (true) or headed (false) mode
  • viewport: Sets the default viewport size
  • locale: Configures the browser’s language (such as en-US)
  • timezoneId: Sets the browser’s timezone (such as America/New_York)
  • device: Emulates a specific device from Playwright’s device list (such as iPhone 16)

The following is an example:

export default defineConfig({
  use: {
    browserName: 'firefox',
    headless: false,
    viewport: { width: 1920, height: 1080 },
    locale: 'en-GB',
    timezoneId: 'Europe/London',
    device: 'Desktop Firefox',
  },
});

Parallelism and workers

These options manage how tests are executed in parallel and across CPU resources:

  • workers: Number of parallel test workers. Set to a number (such as 4) or '50%' to use half the CPU cores
  • fullyParallel: Enables (true) or disables (false) running tests in parallel within a single file

The following is an example:

export default defineConfig({
  workers: 3, // Run 3 tests in parallel
  fullyParallel: true,
});

Retries and failure handling

These settings help control test retries and when the test run should stop after failures:

  • retries: Controls how many times a failed test will be retried before it’s marked as failed
  • maxFailures: Sets a global threshold for how many test failures are allowed before Playwright stops the entire test run

The following is an example:

export default defineConfig({
  retries: 2, // Retry failed tests twice
  maxFailures: 10, // Stop after 10 failures
});

Reporters

Now we come to reporter. Playwright supports multiple reporters for test output. Options include list, dot, line, json, junit, html, or custom reporters.

The following is an example:

export default defineConfig({
  reporter: [
    ['list'], // Console output
    ['html', { outputFolder: 'playwright-report' }], // HTML report
    ['json', { outputFile: 'test-results.json' }], // JSON report
  ],
});

To view the HTML report, run the following:

npx playwright show-report

When Playwright runs in a CI/CD pipeline (which is usually headless), the command to open a browser may hang, which causes the entire pipeline job to get stuck and eventually time out. When running in CI/CD, explicitly set the open option to 'never' for the HTML reporter in the configuration file:

export default defineConfig({
  reporter: [
    ['list'],
    ['html', { outputFolder: 'playwright-report', open: 'never' }],
    ['json', { outputFile: 'test-results.json' }],
  ],
});

Projects for multi-browser testing

The projects property allows you to define multiple test configurations (such as for different browsers or devices). Each project inherits global settings but can override them.

The following is an example:

export default defineConfig({
  projects: [
    {
      name: 'Chromium',
      use: { browserName: 'chromium' },
    },
    {
      name: 'Firefox',
      use: { browserName: 'firefox' },
    },
    {
      name: 'Mobile Safari',
      use: { device: 'iPhone 16' },
    },
  ],
});

Run tests for a specific project:

npx playwright test --project=Chromium

Debugging configuration issues

If your tests fail because of a configuration issue. Start by checking the syntax to make sure your configuration file is correct in TypeScript. Next, check the logs by running the tests with the --debug flag using the npx playwright test --debug command to get a closer look at Playwright’s behavior. If you’re still stuck, try temporarily reverting to the default settings to help isolate the problem. Lastly, make sure you’re using the latest version of Playwright by running npm install @playwright/test@latest to stay up to date.

With your development and testing environments properly configured, you’re now ready to dive into the core functionality of Playwright.

CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Hands-On Automated Testing with Playwright
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist download Download options font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon