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.
Open your terminal and create a new directory for your Playwright project:
mkdir playwright-demo cd playwright-demo
Initialize a new package.json file:
npm init -y
Install Playwright and its browsers:
npm install -D playwright
This will install Playwright and download Chromium, Firefox, and WebKit browsers.
Check Playwright version:
npx playwright --version
If you see a version number, Playwright is installed successfully.
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
For more advanced usage, visit the Playwright Documentation.
To use Playwright with BDD (Behavior Driven Development), install @playwright/test and @cucumber/cucumber:
npm install -D @playwright/test @cucumber/cucumber
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
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"
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();
});
Add a cucumber.js config file for running specs:
module.exports = {
default: '--require features/step-definitions/*.js features/*.feature'
};
Execute your feature files using Cucumber:
npx cucumber-js
Before and After hooks for setup/teardown.Background and Scenario Outline for data-driven tests.expect assertions for better validation.support folder.