Playwright Installation Guide

Step 1: Prerequisites

Make sure you have Node.js (version 14 or higher) installed on your system.

Check Node.js version:

node -v

If you don't have Node.js, download and install it from nodejs.org.

Step 2: Create a New Project Folder

Open your terminal and create a new directory for your Playwright project:

mkdir playwright-demo
cd playwright-demo

Step 3: Initialize npm

Initialize a new package.json file:

npm init -y

Step 4: Install Playwright

Install Playwright and its browsers:

npm install -D playwright

This will install Playwright and download Chromium, Firefox, and WebKit browsers.

Step 5: Verify Installation

Check Playwright version:

npx playwright --version

If you see a version number, Playwright is installed successfully.

Step 6: Run a Sample Test

Create a file named example.spec.js with the following content:

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

test('basic test', async ({ page }) => {
  await page.goto('https://playwright.dev/');
  await expect(page).toHaveTitle(/Playwright/);
});
      

Run the test:

npx playwright test example.spec.js

Step 7: Explore Playwright Docs

For more advanced usage, visit the Playwright Documentation.

Step 8: Install Playwright Test and Cucumber (BDD)

To use Playwright with BDD (Behavior Driven Development), install @playwright/test and @cucumber/cucumber:

npm install -D @playwright/test @cucumber/cucumber

Step 9: Set Up Cucumber Directory Structure

Create a features folder for your BDD specs and step definitions:

/playwright-demo
  /features
    example.feature
    /step-definitions
      example.steps.js
  playwright.config.js
  package.json
  

Step 10: Write a Sample Feature File (example.feature)

Use Gherkin syntax for your BDD scenarios:

Feature: Playwright BDD Example

  Scenario: Open Playwright website and check title
    Given I open the Playwright homepage
    Then the page title should contain "Playwright"
  

Step 11: Create Step Definitions (example.steps.js)

Map Gherkin steps to Playwright actions:

const { Given, Then } = require('@cucumber/cucumber');
const { chromium } = require('playwright');

let page, browser;

Given('I open the Playwright homepage', async function () {
  browser = await chromium.launch();
  page = await browser.newPage();
  await page.goto('https://playwright.dev/');
});

Then('the page title should contain {string}', async function (expectedTitle) {
  const title = await page.title();
  if (!title.includes(expectedTitle)) {
    throw new Error(`Expected "${expectedTitle}" in title, but got "${title}"`);
  }
  await browser.close();
});
  

Step 12: Configure Cucumber

Add a cucumber.js config file for running specs:

module.exports = {
  default: '--require features/step-definitions/*.js features/*.feature'
};
  

Step 13: Run Your BDD Tests

Execute your feature files using Cucumber:

npx cucumber-js

Step 14: Advanced BDD Usage

Step 15: Resources