1. Introduction
Behavior-Driven Development (BDD) is a software development approach that encourages collaboration between developers, testers, and business stakeholders. It helps teams describe application behavior using simple, understandable language before implementing automated tests.
Cucumber is a popular BDD tool that supports Gherkin, a language used to write test scenarios in a readable format. Playwright is a browser automation library that supports end-to-end testing across Chromium, Firefox, and WebKit.
When combined, these tools allow QA engineers to write business-readable scenarios and automate them using browser interactions.
A Playwright BDD framework with Cucumber connects three important layers:
- Feature files describe application behavior.
- Step definitions connect Gherkin steps to TypeScript code.
- Playwright performs browser actions and verifies application behavior.
For example, an online shopping application might contain this scenario:
Scenario: User logs in successfully
Given the user is on the login page
When the user enters valid credentials
And clicks the login button
Then the dashboard should be displayed
A business analyst can understand this scenario, while an automation engineer can implement the steps using Playwright.
In this tutorial, we will build a practical Playwright Cucumber framework using TypeScript, feature files, hooks, a custom World, and the Page Object Model.
2. What Is Playwright BDD Framework with Cucumber?
A Playwright BDD framework with Cucumber combines Cucumber’s BDD capabilities with Playwright’s browser automation features.
Cucumber manages scenarios and executes step definitions. Playwright launches browsers, creates pages, interacts with web elements, and verifies application behavior.
The framework uses four important concepts.
Gherkin syntax
Gherkin is a business-readable language used to describe application behavior.
Its commonly used keywords include:
| Keyword | Purpose |
| Feature | Describes a functionality |
| Scenario | Describes one test case |
| Given | Defines the initial condition |
| When | Defines an action |
| Then | Defines the expected result |
| And | Adds another step |
| But | Describes an additional condition |
| Scenario Outline | Runs a scenario with multiple data sets |
Feature files
Feature files use the .feature extension and contain Gherkin scenarios.
Example:
Feature: User Login
Scenario: Successful login
Given the user is on the login page
When the user enters valid credentials
Then the dashboard should be displayed
Step definitions
Step definitions are TypeScript functions that implement the steps written in feature files.
For example, the following step definition connects a Gherkin statement to Playwright:
Given(‘the user is on the login page’, async function () {
await this.loginPage.open();
});
Browser automation
Playwright performs the actual browser interactions. It can fill forms, click buttons, navigate between pages, handle multiple browser contexts, and capture screenshots.
The overall execution flow is:
Feature File
|
v
Cucumber Scenario
|
v
Step Definitions
|
v
Page Object Methods
|
v
|
v
Application Verification
3. Benefits of BDD with Cucumber
Using Cucumber with Playwright TypeScript provides several benefits for automation teams.
| Benefit | Explanation |
| Readable test cases | Scenarios use simple business language |
| Better collaboration | Testers, developers, and business teams can review scenarios |
| Reusable steps | Common steps can be reused across scenarios |
| Maintainability | Page objects separate browser logic from test scenarios |
| Business-focused testing | Scenarios describe expected application behavior |
| Browser automation | Playwright supports modern browser automation |
BDD is especially useful when a project has detailed business requirements and multiple teams need to understand the expected behavior.
However, BDD is not necessary for every automation project. For small technical test suites, direct Playwright scripts may be simpler.
4. Prerequisites and Project Setup
Before creating the framework, install the following tools:
- Node.js and npm
- Visual Studio Code or another TypeScript editor
- Basic TypeScript knowledge
- Basic Playwright knowledge
- Understanding of Gherkin syntax
Step 1: Create a project
Open the terminal and execute:
mkdir playwright-cucumber-framework
cd playwright-cucumber-framework
npm init -y
Step 2: Install dependencies
Install Playwright, Cucumber, TypeScript, and the TypeScript execution tools.
npm install -D @cucumber/cucumber playwright typescript ts-node @types/node
Install the browser binaries:
Step 3: Configure TypeScript
Create a tsconfig.json file.
{
“compilerOptions”: {
“target”: “ES2020”,
“module”: “CommonJS”,
“moduleResolution”: “Node”,
“strict”: true,
“esModuleInterop”: true,
“skipLibCheck”: true,
“outDir”: “dist”
},
“include”: [“features/**/*.ts”, “src/**/*.ts”]
}
This configuration allows TypeScript files to be compiled using CommonJS modules.
Step 4: Configure package scripts
Update the scripts section in package.json.
{
“scripts”: {
“test”: “cucumber-js”,
“test:smoke”: “cucumber-js –tags @smoke”,
“test:headed”: “HEADLESS=false cucumber-js”,
“typecheck”: “tsc –noEmit”
}
}
The test:headed script uses Unix-style environment variable syntax. On Windows PowerShell, set the variable separately before running Cucumber, or use a cross-platform environment-variable utility such as cross-env.
5. Project Folder Structure
A maintainable framework separates feature files, step definitions, browser setup, and page objects.
Recommended structure:
playwright-cucumber-framework/
|
├── features/
│ ├── login.feature
│ ├── step-definitions/
│ │ └── login.steps.ts
│ └── support/
│ ├── world.ts
│ └── hooks.ts
|
├── src/
│ └── pages/
│ └── LoginPage.ts
|
├── reports/
├── artifacts/
├── cucumber.js
├── package.json
└── tsconfig.json
| Folder or file | Responsibility |
| features | Stores Gherkin feature files |
| step-definitions | Contains TypeScript step implementations |
| support | Contains hooks and World configuration |
| pages | Stores reusable Page Object classes |
| reports | Stores Cucumber execution reports |
| artifacts | Stores screenshots and trace files |
| cucumber.js | Configures Cucumber execution |
This structure makes it easier to expand the framework as new application modules are automated.
6. Writing Feature Files
Feature files describe application behavior without including browser automation code.
Create features/login.feature.
@regression
Feature: Login functionality
As a registered user
I want to log in to the application
So that I can access my dashboard
@smoke
Scenario: Successful login with valid credentials
Given the user is on the login page
When the user enters valid credentials
And clicks the login button
Then the dashboard should be displayed
@negative
Scenario: Login with invalid credentials
Given the user is on the login page
When the user enters invalid credentials
And clicks the login button
Then an error message should be displayed
The first scenario checks successful authentication. The second scenario verifies that invalid credentials are rejected.
Scenario Outline
A Scenario Outline allows the same scenario to execute with different data sets.
Scenario Outline: Login with different credentials
Given the user is on the login page
When the user enters “<username>” and “<password>”
And clicks the login button
Then the login result should be “<result>”
Examples:
| username | password | result |
| admin | admin123 | success |
| testuser | wrong123 | failure |
Cucumber executes the scenario once for every row in the Examples table.
7. Creating Step Definitions
Step definitions connect feature-file statements to executable TypeScript code.
Create features/step-definitions/login.steps.ts.
import { Given, When, Then } from ‘@cucumber/cucumber’;
import assert from ‘node:assert/strict’;
import { CustomWorld } from ‘../support/world’;
Given(
‘the user is on the login page’,
async function (this: CustomWorld) {
await this.loginPage.open();
}
);
When(
‘the user enters valid credentials’,
async function (this: CustomWorld) {
await this.loginPage.login(‘admin’, ‘admin123’);
}
);
When(
‘clicks the login button’,
async function (this: CustomWorld) {
await this.loginPage.clickLogin();
}
);
Then(
‘the dashboard should be displayed’,
async function (this: CustomWorld) {
const visible = await this.loginPage.isDashboardVisible();
assert.equal(visible, true);
}
);
When(
‘the user enters invalid credentials’,
async function (this: CustomWorld) {
await this.loginPage.login(‘wronguser’, ‘wrongpass’);
}
);
Then(
‘an error message should be displayed’,
async function (this: CustomWorld) {
const visible = await this.loginPage.isErrorVisible();
assert.equal(visible, true);
}
);
The functions use this to access the custom World. Regular function expressions are important here because arrow functions do not receive Cucumber’s World as their this value.
The example uses Node.js assertions rather than Playwright Test’s expect. This keeps the assertion layer independent of Playwright Test’s runner.
8. Integrating Playwright with Cucumber
Cucumber and Playwright have separate responsibilities.
Cucumber controls the test execution lifecycle. Playwright provides the browser, context, and page objects.
Create a custom World
The World is a scenario-specific context that allows step definitions and hooks to share objects.
Create features/support/world.ts.
import {
World,
IWorldOptions,
setWorldConstructor
} from ‘@cucumber/cucumber’;
import {
BrowserContext,
Page
} from ‘playwright’;
import { LoginPage } from ‘../../src/pages/LoginPage’;
export class CustomWorld extends World {
context!: BrowserContext;
page!: Page;
loginPage!: LoginPage;
constructor(options: IWorldOptions) {
super(options);
}
}
setWorldConstructor(CustomWorld);
Each scenario receives its own World instance. This helps prevent test data and browser state from leaking between scenarios.
Create Cucumber hooks
Create features/support/hooks.ts.
import {
BeforeAll,
AfterAll,
Before,
After,
Status
} from ‘@cucumber/cucumber’;
import { chromium, Browser } from ‘playwright’;
import { mkdir, readFile } from ‘node:fs/promises’;
import path from ‘node:path’;
import { CustomWorld } from ‘./world’;
import { LoginPage } from ‘../../src/pages/LoginPage’;
let browser: Browser;
BeforeAll(async function () {
browser = await chromium.launch({
headless: process.env.HEADLESS !== ‘false’
});
await mkdir(‘artifacts/traces’, { recursive: true });
});
Before(async function (this: CustomWorld) {
this.context = await browser.newContext();
this.page = await this.context.newPage();
this.loginPage = new LoginPage(this.page);
await this.context.tracing.start({
screenshots: true,
snapshots: true
});
});
After(async function (
this: CustomWorld,
{ result }
) {
if (!this.context) return;
if (result?.status === Status.FAILED) {
const screenshot = await this.page.screenshot();
await this.attach(screenshot, ‘image/png’);
const tracePath = path.join(
‘artifacts/traces’,
`trace-${Date.now()}.zip`
);
await this.context.tracing.stop({
path: tracePath
});
await this.attach(
await readFile(tracePath),
‘application/zip’
);
} else {
await this.context.tracing.stop();
}
await this.context.close();
});
AfterAll(async function () {
await browser?.close();
});
The hooks perform browser setup and cleanup.
- BeforeAll launches the browser once for the run.
- Before creates a fresh context and page for each scenario.
- After captures failure evidence and closes the scenario context.
- AfterAll closes the browser.
The example uses Chromium. Additional browser projects can be created by selecting Firefox or WebKit and running separate configurations.
9. Real-World Login Test Example
Now create the Page Object Model class.
Create src/pages/LoginPage.ts.
import { Page } from ‘playwright’;
export class LoginPage {
constructor(private page: Page) {}
async open() {
await this.page.goto(
‘https://your-application-url.com/login’
);
}
async login(username: string, password: string) {
await this.page.getByLabel(‘Username’).fill(username);
await this.page.getByLabel(‘Password’).fill(password);
}
async clickLogin() {
await this.page.getByRole(‘button’, {
name: ‘Login’
}).click();
}
async isDashboardVisible() {
return await this.page.getByRole(‘heading’, {
name: ‘Dashboard’
}).isVisible();
}
async isErrorVisible() {
return await this.page.getByText(
‘Invalid username or password’
).isVisible();
}
}
Replace the URL and accessible labels with the actual values from your application. The example assumes that the application displays a Dashboard heading after successful login and the specified error text after an unsuccessful login.
Configure Cucumber
Create cucumber.js.
module.exports = {
default: {
paths: [‘features/**/*.feature’],
requireModule: [‘ts-node/register’],
require: [
‘features/support/*.ts’,
‘features/step-definitions/*.ts’
],
format: [
‘progress’,
‘html:reports/cucumber-report.html’,
‘json:reports/cucumber-report.json’
],
publishQuiet: true
}
};
The configuration tells Cucumber where to find feature files and TypeScript support code. The ts-node/register option allows Cucumber to load TypeScript files at runtime.
Execute the framework
Run the following commands:
npm run typecheck
npm test
To run only smoke scenarios:
npm run test:smoke
To run the browser in headed mode, set HEADLESS=false in the environment before executing Cucumber.
Expected results:
- Cucumber discovers the feature files.
- The browser opens using Playwright.
- Step definitions execute the login workflow.
- Cucumber reports passed and failed scenarios.
- Failure screenshots and trace files are saved as artifacts.
The login test will only pass when the application URL, locators, credentials, and expected messages match the target application.
10. Advanced BDD Features
Data Tables
Data Tables allow multiple values to be passed to a single Gherkin step.
Scenario: Login with user details
Given the user is on the login page
When the user enters these credentials:
| username | password |
| admin | admin123 |
A step definition can access the table:
When(
‘the user enters these credentials:’,
async function (this: CustomWorld, dataTable) {
const users = dataTable.hashes();
for (const user of users) {
await this.loginPage.login(
user.username,
user.password
);
}
}
);
For a login form, normally one row is appropriate because entering multiple users sequentially without submitting or resetting the form may not represent separate login tests. Use Scenario Outline when each row should be an independent scenario.
Tags
Tags help organize and selectively execute scenarios.
@smoke
Scenario: Successful login
npx cucumber-js –tags “@smoke”
Run regression tests:
npx cucumber-js –tags “@regression”
Tags can also be used to control hooks for particular scenarios.
Hooks
Cucumber hooks support setup and teardown operations.
Common hooks include:
- Before: Runs before each scenario.
- After: Runs after each scenario.
- BeforeAll: Runs before the scenario execution begins.
- AfterAll: Runs after all scenarios finish.
- BeforeStep and AfterStep: Run around individual steps.
Use hooks for browser setup, authentication preparation, test data initialization, and cleanup.
World context and Page Object Model
The custom World provides scenario-level state. The Page Object Model stores locators and browser actions.
This separation creates a clear framework architecture:
Feature File
|
Step Definition
|
Custom World
|
Page Object
|
Playwright Page
Avoid putting every browser action directly inside step definitions. Keep step definitions focused on connecting business language to application workflows.
11. Reporting and Debugging
Reporting is important because QA engineers need to understand which scenarios passed, failed, or were skipped.
The example configuration generates HTML and JSON reports.
After execution, open:
reports/cucumber-report.html
Cucumber also supports different formatters and third-party reporting integrations. Teams can select a reporting solution based on their project requirements.
Screenshots on failure
The After hook captures a screenshot when a scenario fails and attaches it to the Cucumber result.
This helps testers inspect the browser state at the time of failure.
Playwright traces
The example records Playwright traces and attaches the trace ZIP to failed scenarios.
Open a saved trace using:
npx playwright show-trace artifacts/traces/trace-file.zip
Replace the example filename with the actual trace file.
Trace Viewer helps inspect browser actions, DOM snapshots, screenshots, and network activity. Note that Playwright’s tracing API does not record Playwright Test assertions. This example uses Node.js assertions with Cucumber, so browser-action traces are useful for investigating failures.
12. CI/CD Integration
A BDD framework should execute automatically during development and release workflows.
GitHub Actions can install dependencies, install browser binaries, run Cucumber, and upload reports.
Create .github/workflows/bdd-tests.yml.
name: Playwright Cucumber Tests
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
bdd-tests:
runs-on: ubuntu-latest
steps:
– name: Checkout repository
uses: actions/checkout@v4
– name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
– name: Install dependencies
run: npm ci
– name: Install Playwright browsers
run: npx playwright install –with-deps chromium
– name: TypeScript validation
run: npm run typecheck
– name: Execute BDD tests
run: npm test
– name: Upload reports and artifacts
if: always()
uses: actions/upload-artifact@v4
with:
name: cucumber-test-results
path: |
reports/
artifacts/
Commit the package-lock.json file so npm ci can install the locked dependencies.
For Jenkins, create a Pipeline job that checks out the repository, installs Node.js dependencies, installs Chromium, and executes npm test. Archive the reports and artifacts directories so the team can inspect execution results.
13. Best Practices and Common Mistakes
Follow these practices when developing a Playwright Cucumber framework.
| Best practice | Why it matters |
| Write business-readable Gherkin | Makes scenarios understandable |
| Keep steps reusable | Reduces duplicate automation code |
| Use Page Object Model | Separates locators from business steps |
| Create a new context per scenario | Improves test isolation |
| Use meaningful tags | Supports selective execution |
| Capture failure evidence | Makes debugging easier |
| Store credentials securely | Protects sensitive test data |
| Keep scenarios independent | Reduces execution dependencies |
Common mistakes include:
- Writing long Gherkin scenarios that contain too many unrelated actions.
- Creating duplicate step definitions with similar wording.
- Putting all Playwright code inside feature step files.
- Sharing one browser page across unrelated scenarios.
- Using fixed waits instead of Playwright’s locator and navigation waiting behavior.
- Using Cucumber and Playwright Test as if they were the same test runner.
- Hardcoding real passwords or production credentials in feature files.
- Enabling parallel execution without checking shared test data and application state.
Start with sequential execution. Introduce parallel execution after confirming that each scenario has independent browser state and test data.
14. Interview Questions and FAQs
1. Is Playwright BDD framework with Cucumber suitable for beginners?
Yes. Beginners can start by learning Gherkin keywords, writing simple feature files, and connecting steps to TypeScript functions. Understanding basic Playwright browser automation makes the learning process easier.
2. What are the benefits of Playwright BDD framework with Cucumber?
It provides readable test scenarios, better collaboration, reusable step definitions, and maintainable browser automation. It is useful when business stakeholders need to review automated acceptance tests.
3. How do I get started with Playwright BDD framework with Cucumber?
Install Node.js, Playwright, Cucumber, and TypeScript. Create a feature file, write step definitions, configure browser hooks, and connect the steps to reusable page objects.
4. What is the difference between Playwright Test and Cucumber?
Playwright Test is Playwright’s built-in test runner. It provides fixtures, assertions, parallel execution, and reporting. Cucumber is a separate BDD test runner that executes Gherkin scenarios through step definitions. Playwright can be used as the browser automation library with Cucumber.
5. What is a feature file in Cucumber?
A feature file is a .feature file that describes application functionality using Gherkin syntax. It contains features, scenarios, steps, and optionally tags or examples.
6. What is the purpose of step definitions?
Step definitions connect Gherkin steps to executable code. They contain TypeScript functions that call page objects and perform browser actions.
7. What is the World object in Cucumber?
World is a scenario-specific context. It allows steps and hooks to share data and objects during one scenario. A custom World can store the Playwright page, browser context, and page object instances.
8. How do you take screenshots when a scenario fails?
Use Cucumber’s After hook, check the scenario result status, capture a screenshot using page.screenshot(), and attach the image using this.attach().
9. Can we use Page Object Model with Cucumber?
Yes. Page Object Model keeps locators and browser actions in separate classes. Step definitions call page object methods, making the automation code easier to maintain.
10. How can you run only smoke tests?
Add the @smoke tag to the required scenarios and execute:
npx cucumber-js –tags “@smoke”
