Playwright with Cucumber BDD Setup Guide
Step 1: Install Node.js
Ensure Node.js is installed by running:
node -v
npm -v
If not installed, download from Node.js Official Website.
Step 2: Create a New Project
mkdir playwright-bdd-project
cd playwright-bdd-project
npm init -y
Step 3: Install Dependencies
npm install playwright @cucumber/cucumber --save-dev
Step 4: Create Project Structure
/playwright-bdd-project
├── /features
│ ├── sample.feature
│ └── steps.js
├── /pages
│ └── homePage.js
├── cucumber.js
├── package.json
└── README.md
Step 5: Create a Feature File
# sample.feature
Feature: Sample Test with Playwright and Cucumber
Scenario: Verify homepage title
Given I navigate to "https://example.com"
Then the page title should be "Example Domain"
Step 6: Create Step Definitions
// steps.js
const { Given, Then } = require('@cucumber/cucumber');
const { chromium } = require('playwright');
let browser, page;
Given('I navigate to {string}', async (url) => {
browser = await chromium.launch();
page = await browser.newPage();
await page.goto(url);
});
Then('the page title should be {string}', async (expectedTitle) => {
const title = await page.title();
if (title !== expectedTitle) {
throw new Error(`Expected ${expectedTitle} but got ${title}`);
}
await browser.close();
});
Step 7: Create `cucumber.js` Configuration File
module.exports = {
default: "./features/**/*.feature --require ./features/**/*.js"
};
Step 8: Add Test Script in `package.json`
"scripts": {
"test": "cucumber-js"
}
Step 9: Run Your Tests
npm test
Step 10: Additional Tips
- âś… Use `.env` files to manage environment variables.
- âś… Add `before()` and `after()` hooks for setup and teardown logic.
- âś… Consider adding ESLint for clean and consistent code.