Playwright BDD Framework with TypeScript: Step-by-Step Guide

BDD (Behaviour-Driven Development) lets testers, developers and business people agree on behaviour in plain English before anyone writes code. In this step-by-step guide you will build a complete Playwright BDD framework with TypeScript using playwright-bdd: Gherkin feature files, step definitions, Page Objects injected as fixtures, Scenario Outlines, data tables, tags, hooks, two HTML reports and a CI workflow. Every file below was run against the SQA Tools practice shop, and the outputs are real.

Advertisement

📖 What You’ll Learn: how playwright-bdd turns Gherkin into Playwright tests, project setup, defineBddConfig, writing features and step definitions, Page Objects as fixtures, Scenario Outline and Examples, data tables, Background, tags and smoke runs, hooks, missing-step errors, Playwright and Cucumber HTML reports, GitHub Actions, and common BDD interview questions.


🧭 What Is playwright-bdd and Why Use It?

In the previous lesson you connected Playwright to Cucumber-JS. That works, but Cucumber is the test runner there, so you lose most of what makes Playwright Test good: fixtures, auto-cleanup, parallel workers, retries, traces and the HTML report. You end up writing your own browser hooks and a shared page variable.

playwright-bdd takes the opposite approach. A small command, bddgen, reads your .feature files and generates normal Playwright test files. Then npx playwright test runs them. You write Gherkin and step definitions; Playwright Test does the rest.

TopicCucumber-JS + Playwright libraryplaywright-bdd + Playwright Test
Test runnercucumber-jsPlaywright Test (npx playwright test)
Browser and page setupYou write BeforeAll / Before hooksBuilt-in page fixture, cleaned up automatically
Page ObjectsCreated in the World or in stepsInjected into steps as fixtures
Parallel runs--parallel, shared state is riskyPlaywright workers, fullyParallel, sharding
Traces, screenshots, videoManualtrace / screenshot options in the config
ReportsCucumber formattersPlaywright HTML report and Cucumber reports
Run one test in the IDENeeds a Cucumber pluginWorks with the Playwright VS Code extension (on generated files)

Choose Cucumber-JS when a team already has a large Cucumber suite or needs a Cucumber-only plugin. For a new Playwright framework, playwright-bdd is usually the better fit.


🧰 Step 1: Create the Project and Install Packages

You need Node.js 20 or newer (this guide used Node.js 26.13.0) and a code editor. If Playwright is new to you, read Install Playwright first. Versions used in this guide (checked on 24 November 2026): @playwright/test 1.65.1, playwright-bdd 9.2.1, typescript 7.0.2.

⌨️ Terminal

mkdir playwright-bdd-shop
cd playwright-bdd-shop
npm init -y
npm install -D @playwright/test playwright-bdd typescript @types/node dotenv
npx playwright install chromium
  • @playwright/test: the Playwright test runner and browsers API.
  • playwright-bdd: the bddgen generator plus createBdd() for step definitions. It also installs the Gherkin parser and Cucumber expressions, so you do not install @cucumber/cucumber.
  • dotenv: reads the .env file so URLs and users are not hard-coded.

📁 Step 2: Plan the Folder Structure

Keep the three BDD layers apart: features describe behaviour, steps translate each sentence into code, and pages hold locators and actions. Steps should stay thin and call Page Object methods.

📁 Project structure

playwright-bdd-shop/
├── features/              # Gherkin: what the app should do
│   ├── login.feature
│   ├── search.feature
│   └── cart.feature
├── steps/                 # Step definitions: glue between Gherkin and pages
│   ├── fixtures.ts        # Page Object fixtures + Given/When/Then
│   ├── hooks.steps.ts
│   ├── login.steps.ts
│   └── shop.steps.ts
├── pages/                 # Page Object Model: locators and actions
│   ├── LoginPage.ts
│   ├── ProductListPage.ts
│   └── CartPage.ts
├── .features-gen/         # generated by bddgen (do not edit, do not commit)
├── .env
├── playwright.config.ts
├── tsconfig.json
└── package.json

The app under test is the free SQA Tools dummy e-commerce website. Every element has a stable data-testid, and it has demo users: testuser / Test@123 (valid) and lockeduser / Test@123 (locked).


⚙️ Step 3: Configure Playwright with defineBddConfig

defineBddConfig() tells playwright-bdd where your features and steps are. It returns the folder where generated tests are written (.features-gen by default), and you pass that folder to Playwright as testDir.

📄 playwright.config.ts

import { defineConfig, devices } from '@playwright/test';
import { defineBddConfig, cucumberReporter } from 'playwright-bdd';
import 'dotenv/config';

const testDir = defineBddConfig({
  features: 'features/**/*.feature',
  steps: ['steps/fixtures.ts', 'steps/**/*.steps.ts'],
});

export default defineConfig({
  testDir,
  fullyParallel: true,
  retries: process.env.CI ? 2 : 0,
  reporter: [
    ['list'],
    ['html', { open: 'never' }],
    cucumberReporter('html', { outputFile: 'cucumber-report/index.html' }),
  ],
  use: {
    baseURL: process.env.BASE_URL ?? 'https://sqatools.in/dummy-ecommerce-website/',
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
  },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
  ],
});
  • features and steps are glob patterns. Always use forward slashes, even on Windows.
  • steps lists fixtures.ts first because it creates the Given, When and Then functions the other step files import.
  • cucumberReporter('html') adds a Cucumber-style HTML report next to Playwright’s own report.
  • baseURL comes from .env, so page.goto('#/login') works against any environment.

📄 .env

BASE_URL=https://sqatools.in/dummy-ecommerce-website/
SHOP_USER=testuser
SHOP_PASSWORD=Test@123

📄 tsconfig.json

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "preserve",
    "moduleResolution": "bundler",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "noEmit": true,
    "types": ["node"]
  }
}

⚠️ Watch out: Add .env to .gitignore once it holds real passwords, and set the same variables as CI secrets. The demo values here are public test data.


📝 Step 4: Write Your First Feature File

A feature file describes one feature in Gherkin. Write it from the user’s point of view, with no locators or code words in it.

📄 features/login.feature

@login
Feature: Login
  As a shopper
  I want to log in to the SQA Shop
  So that I can see my account

  Background:
    Given I am on the login page

  @smoke
  Scenario: Successful login with the default user
    When I log in with the default user
    Then I should see the greeting "Hi, Test"

  Scenario Outline: Login fails for <case>
    When I log in as "<username>" with password "<password>"
    Then I should see the login error "<message>"

    Examples:
      | case           | username   | password | message                                         |
      | wrong password | testuser   | wrong    | Invalid username or password.                   |
      | locked account | lockeduser | Test@123 | This account is locked. Please contact support. |
      | empty fields   |            |          | Username and password are required.             |
KeywordMeaning
FeatureThe feature under test, plus an optional user story (As a / I want / So that).
BackgroundSteps that run before every scenario in this file, like beforeEach.
ScenarioOne example of behaviour. Becomes one Playwright test.
Given / When / ThenContext, action, expected outcome. And and But continue the previous type.
Scenario Outline + ExamplesOne scenario run once per table row. <username> is replaced with the row value.
@smoke, @loginTags. A feature tag applies to all its scenarios. Use them to filter runs.

🧱 Step 5: Build the Page Objects

Page Objects keep locators in one place. If the login button changes, you fix one line, not every step. (See Page Object Model in Playwright for the full pattern.)

📄 pages/LoginPage.ts

import { Page, Locator, expect } from '@playwright/test';

export class LoginPage {
  readonly username: Locator;
  readonly password: Locator;
  readonly loginButton: Locator;
  readonly error: Locator;
  readonly accountLabel: Locator;

  constructor(private readonly page: Page) {
    this.username = page.getByTestId('login-username');
    this.password = page.getByTestId('login-password');
    this.loginButton = page.getByTestId('login-button');
    this.error = page.getByTestId('login-error');
    this.accountLabel = page.locator('#account-label');
  }

  async open() {
    await this.page.goto('#/login');
    await expect(this.loginButton).toBeVisible();
  }

  async login(user: string, pass: string) {
    await this.username.fill(user);
    await this.password.fill(pass);
    await this.loginButton.click();
  }
}
  • Locators use getByTestId(), the most stable option on this site.
  • open() waits for the login button with a web-first assertion, so steps never start on a half-loaded page.
  • No assertions about results live here. Checking outcomes is the job of Then steps.

Advertisement

🧩 Step 6: Register Page Objects as Fixtures

This is the key difference from Cucumber-JS. Instead of a global page variable, you extend Playwright’s test with one custom fixture per Page Object. Then you pass that test to createBdd(), which returns step functions that can ask for those fixtures by name.

📄 steps/fixtures.ts

import { test as base, createBdd } from 'playwright-bdd';
import { LoginPage } from '../pages/LoginPage';
import { ProductListPage } from '../pages/ProductListPage';
import { CartPage } from '../pages/CartPage';

type Pages = {
  loginPage: LoginPage;
  productListPage: ProductListPage;
  cartPage: CartPage;
};

export const test = base.extend<Pages>({
  loginPage: async ({ page }, use) => {
    await use(new LoginPage(page));
  },
  productListPage: async ({ page }, use) => {
    await use(new ProductListPage(page));
  },
  cartPage: async ({ page }, use) => {
    await use(new CartPage(page));
  },
});

export const { Given, When, Then, Before, After } = createBdd(test);
  • Import test from playwright-bdd (not from @playwright/test). It already contains the BDD runtime fixtures.
  • Each fixture is created only when a step in that scenario uses it, and each scenario gets its own fresh page, so parallel runs never share state.
  • Every step file imports Given, When, Then from this file, so all steps get full TypeScript types for loginPage, productListPage and cartPage.

🔗 Step 7: Write the Step Definitions

A step definition matches a Gherkin sentence and runs code. The first argument is an object of fixtures; the next arguments are the values captured from the sentence.

📄 steps/login.steps.ts

import { expect } from '@playwright/test';
import { Given, When, Then } from './fixtures';

Given('I am on the login page', async ({ loginPage }) => {
  await loginPage.open();
});

When('I log in as {string} with password {string}', async ({ loginPage }, user: string, pass: string) => {
  await loginPage.login(user, pass);
});

When('I log in with the default user', async ({ loginPage }) => {
  await loginPage.login(process.env.SHOP_USER!, process.env.SHOP_PASSWORD!);
});

Then('I should see the greeting {string}', async ({ loginPage }, greeting: string) => {
  await expect(loginPage.accountLabel).toHaveText(greeting);
});

Then('I should see the login error {string}', async ({ loginPage }, message: string) => {
  await expect(loginPage.error).toHaveText(message);
});
Cucumber expressionMatchesValue passed in
{string}"testuser" or 'testuser'testuser (string, without quotes)
{int}22 (number)
{float}4.54.5 (number)
product(s)product or productsnothing (optional text)

💡 Tip: Run npx bddgen export to print every step your project knows. It is a quick way to reuse an existing sentence instead of writing a near-duplicate.


▶️ Step 8: Generate and Run the Tests

Running is always two commands: bddgen generates test files from the features, then Playwright runs them. Put both in package.json so nobody forgets the first one.

📄 package.json

{
  "name": "playwright-bdd-shop",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "test": "bddgen && playwright test",
    "test:smoke": "bddgen && playwright test --grep @smoke",
    "report": "playwright show-report",
    "steps": "bddgen export"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "type": "commonjs",
  "devDependencies": {
    "@playwright/test": "^1.65.1",
    "@types/node": "^26.6.6",
    "dotenv": "^18.0.10",
    "playwright-bdd": "^9.2.1",
    "typescript": "^7.0.2"
  }
}

⌨️ Terminal

npm test

🖥️ Output

> playwright-bdd-shop@1.0.0 test
> bddgen && playwright test

Running 8 tests using 6 workers

Starting: Add two products and apply a coupon
Starting: Login fails for wrong password
Starting: An invalid coupon is rejected
Starting: Login fails for empty fields
Starting: Login fails for locked account
Starting: Successful login with the default user
  ok 2 [chromium] › .features-gen\features\login.feature.spec.js:17:5 › Login › Login fails for <case> › Login fails for wrong password @login (1.9s)
Starting: Search finds a matching product
  ok 4 [chromium] › .features-gen\features\login.feature.spec.js:10:3 › Login › Successful login with the default user @login @smoke (2.3s)
Starting: Search with no matches shows a message
  ok 3 [chromium] › .features-gen\features\login.feature.spec.js:27:5 › Login › Login fails for <case> › Login fails for empty fields @login (3.1s)
  ok 1 [chromium] › .features-gen\features\cart.feature.spec.js:10:3 › Shopping cart › Add two products and apply a coupon @cart @smoke (3.5s)
  ok 6 [chromium] › .features-gen\features\login.feature.spec.js:22:5 › Login › Login fails for <case> › Login fails for locked account @login (3.5s)
  ok 5 [chromium] › .features-gen\features\cart.feature.spec.js:19:3 › Shopping cart › An invalid coupon is rejected @cart (4.2s)
  ok 7 [chromium] › .features-gen\features\search.feature.spec.js:10:3 › Product search › Search finds a matching product @search @smoke (2.7s)
  ok 8 [chromium] › .features-gen\features\search.feature.spec.js:16:3 › Product search › Search with no matches shows a message @search (2.5s)

  8 passed (6.1s)
  • Eight tests ran: 4 login (1 scenario + 3 outline rows), 2 search and 2 cart, in parallel on 6 workers.
  • Each Scenario Outline row became its own test, named from the <case> column.
  • Tags from the feature file appear on each test, for example @login @smoke.
  • The Starting: lines come from the Before hook you will add in Step 10.

What bddgen generates

Open .features-gen/features/search.feature.spec.js to see that a BDD scenario is just a Playwright test (the technical section at the end is trimmed here):

📄 .features-gen/features/search.feature.spec.js (generated)

// Generated from: features\search.feature
import { test } from "../../steps/fixtures.ts";

test.describe('Product search', () => {

  test.beforeEach('Background', async ({ Given, productListPage }, testInfo) => { if (testInfo.error) return;
    await Given('I am on the shop home page', null, { productListPage }); 
  });
  
  test('Search finds a matching product', { tag: ['@search', '@smoke'] }, async ({ When, Then, And, productListPage }) => { 
    await When('I search for "earbuds"', null, { productListPage }); 
    await Then('I should see 1 product', null, { productListPage }); 
    await And('I should see the product "Wireless Earbuds"', null, { productListPage }); 
  });

  test('Search with no matches shows a message', { tag: ['@search'] }, async ({ When, Then, And, productListPage }) => { 
    await When('I search for "zzzzqq"', null, { productListPage }); 
    await Then('I should see 0 products', null, { productListPage }); 
    await And('I should see the no results message', null, { productListPage }); 
  });

});

Background became test.beforeEach, each scenario became a test() with tags, and only the fixtures each scenario needs are requested. Never edit these files: they are rebuilt on every run. Add .features-gen/ to .gitignore.

Advertisement

When a step is missing

If a feature uses a sentence with no matching step definition, bddgen stops and prints a ready-to-paste snippet. Here a new step When I sort products by "Price: low to high" was added without code:

🖥️ Output

Missing step definitions: 1

When('I sort products by {string}', async ({}, arg: string) => {
  // Step: When I sort products by "Price: low to high"
  // From: features\tmp.feature:4:5
});

Use snippets above to create missing steps.

⚠️ Watch out: Paste the snippet into a step file, then rename arg and add the fixtures you need, for example async ({ productListPage }, sortBy: string). Failing at generation time is a feature: you find missing steps in a second instead of after a long run.


🛒 Step 9: Real Scenario: Search and Cart with Data Tables

Now a realistic flow on the practice shop: search for products, add several items to the cart and apply a coupon. Data tables let one step take a list of values.

📄 features/search.feature

@search
Feature: Product search

  Background:
    Given I am on the shop home page

  @smoke
  Scenario: Search finds a matching product
    When I search for "earbuds"
    Then I should see 1 product
    And I should see the product "Wireless Earbuds"

  Scenario: Search with no matches shows a message
    When I search for "zzzzqq"
    Then I should see 0 products
    And I should see the no results message

📄 features/cart.feature

@cart
Feature: Shopping cart

  Background:
    Given I am on the shop home page

  @smoke
  Scenario: Add two products and apply a coupon
    When I add these products to the cart:
      | product          |
      | RGB Gaming Mouse |
      | 1080p Webcam     |
    Then the cart badge should show 2
    When I open the cart
    Then the cart should contain:
      | product          |
      | RGB Gaming Mouse |
      | 1080p Webcam     |
    When I apply the coupon "SAVE10"
    Then the coupon message should be "Coupon SAVE10 applied."

  Scenario: An invalid coupon is rejected
    When I add these products to the cart:
      | product          |
      | RGB Gaming Mouse |
    And I open the cart
    And I apply the coupon "BOGUS"
    Then the coupon message should be "This coupon code is not valid."

📄 pages/ProductListPage.ts

import { Page, Locator, expect } from '@playwright/test';

export class ProductListPage {
  readonly searchInput: Locator;
  readonly searchButton: Locator;
  readonly listingTitle: Locator;
  readonly resultCount: Locator;
  readonly productNames: Locator;
  readonly noResults: Locator;
  readonly cartCount: Locator;
  readonly cartLink: Locator;

  constructor(private readonly page: Page) {
    this.searchInput = page.getByTestId('search-input');
    this.searchButton = page.getByTestId('search-button');
    this.listingTitle = page.getByTestId('listing-title');
    this.resultCount = page.getByTestId('result-count');
    this.productNames = page.getByTestId('product-name');
    this.noResults = page.getByTestId('no-results');
    this.cartCount = page.getByTestId('cart-count');
    this.cartLink = page.getByTestId('cart-link');
  }

  async open() {
    await this.page.goto('');
    await expect(this.productNames.first()).toBeVisible();
  }

  async search(term: string) {
    await this.searchInput.fill(term);
    await this.searchButton.click();
  }

  /** Clicks "Add to cart" on the card whose product name matches exactly. */
  async addToCart(productName: string) {
    const card = this.page
      .getByTestId('product-card')
      .filter({ has: this.page.getByTestId('product-name').getByText(productName, { exact: true }) });
    await card.getByRole('button', { name: 'Add to cart' }).click();
  }

  async openCart() {
    await this.cartLink.click();
  }
}
  • addToCart() finds the product card that contains the exact product name, then clicks the Add to cart button inside that card. This works no matter where the product appears in the grid.

📄 pages/CartPage.ts

import { Page, Locator } from '@playwright/test';

export class CartPage {
  readonly title: Locator;
  readonly itemNames: Locator;
  readonly couponInput: Locator;
  readonly applyCoupon: Locator;
  readonly couponMessage: Locator;

  constructor(private readonly page: Page) {
    this.title = page.getByTestId('cart-title');
    this.itemNames = page.getByTestId('cart-item-name');
    this.couponInput = page.getByTestId('coupon-input');
    this.applyCoupon = page.getByTestId('apply-coupon');
    this.couponMessage = page.getByTestId('coupon-message');
  }

  async applyCouponCode(code: string) {
    await this.couponInput.fill(code);
    await this.applyCoupon.click();
  }
}

📄 steps/shop.steps.ts

import { expect } from '@playwright/test';
import { DataTable } from 'playwright-bdd';
import { Given, When, Then } from './fixtures';

Given('I am on the shop home page', async ({ productListPage }) => {
  await productListPage.open();
});

When('I search for {string}', async ({ productListPage }, term: string) => {
  await productListPage.search(term);
});

Then('the results title should be {string}', async ({ productListPage }, title: string) => {
  await expect(productListPage.listingTitle).toHaveText(title);
});

Then('I should see {int} product(s)', async ({ productListPage }, count: number) => {
  await expect(productListPage.resultCount).toContainText(`${count} product`);
});

Then('I should see the product {string}', async ({ productListPage }, name: string) => {
  await expect(productListPage.productNames.getByText(name, { exact: true })).toBeVisible();
});

Then('I should see the no results message', async ({ productListPage }) => {
  await expect(productListPage.noResults).toContainText('No products found');
});

When('I add these products to the cart:', async ({ productListPage }, table: DataTable) => {
  for (const row of table.hashes()) {
    await productListPage.addToCart(row.product);
  }
});

Then('the cart badge should show {int}', async ({ productListPage }, count: number) => {
  await expect(productListPage.cartCount).toHaveText(String(count));
});

When('I open the cart', async ({ productListPage }) => {
  await productListPage.openCart();
});

Then('the cart should contain:', async ({ cartPage }, table: DataTable) => {
  const expected = table.hashes().map((row) => row.product);
  await expect(cartPage.itemNames).toHaveText(expected);
});

When('I apply the coupon {string}', async ({ cartPage }, code: string) => {
  await cartPage.applyCouponCode(code);
});

Then('the coupon message should be {string}', async ({ cartPage }, message: string) => {
  await expect(cartPage.couponMessage).toHaveText(message);
});
  • A step that ends with a colon receives a DataTable as its last argument.
  • table.hashes() turns the table into objects using the header row as keys: [{ product: 'RGB Gaming Mouse' }, { product: '1080p Webcam' }].
  • toHaveText(expected) with an array checks every cart line, in order, and retries until it matches.
  • The same step I add these products to the cart: is reused by both cart scenarios.

🏷️ Step 10: Hooks, Tags and Smoke Runs

createBdd() also returns scenario hooks. Before and After run around every scenario and can use any fixture. This one logs the scenario name and attaches a full-page screenshot when a scenario fails:

📄 steps/hooks.steps.ts

import { Before, After } from './fixtures';

Before(async ({ $testInfo }) => {
  console.log(`Starting: ${$testInfo.title}`);
});

After(async ({ page, $testInfo }) => {
  if ($testInfo.status !== $testInfo.expectedStatus) {
    await $testInfo.attach('page-on-failure', {
      body: await page.screenshot({ fullPage: true }),
      contentType: 'image/png',
    });
  }
});

Hooks can be limited by tag, for example Before({ tags: '@cart' }, async ({ page }) => { ... }). Most setup is still better as a fixture: fixtures run only when needed and clean up after themselves.

Advertisement

Run only the smoke scenarios

Tags become Playwright tags, so the normal --grep option filters them:

⌨️ Terminal

npm run test:smoke

🖥️ Output

Running 3 tests using 3 workers

  ok 2 [chromium] › .features-gen\features\search.feature.spec.js:10:3 › Product search › Search finds a matching product @search @smoke (1.8s)
  ok 3 [chromium] › .features-gen\features\login.feature.spec.js:10:3 › Login › Successful login with the default user @login @smoke (1.8s)
  ok 1 [chromium] › .features-gen\features\cart.feature.spec.js:10:3 › Shopping cart › Add two products and apply a coupon @cart @smoke (3.1s)

  3 passed (3.9s)
GoalCommand
Smoke scenarios onlynpx playwright test --grep @smoke
Everything except cartnpx playwright test --grep-invert @cart
Generate only some scenariosnpx bddgen --tags "@login and not @slow"
One feature filenpx playwright test .features-gen/features/login.feature.spec.js
Watch it runnpx playwright test --headed --workers=1

List every step

⌨️ Terminal

npx bddgen export

🖥️ Output

Using config: playwright.config.ts
List of all steps (17):
* Given I am on the login page
* When I log in as {string} with password {string}
* When I log in with the default user
* Then I should see the greeting {string}
* Then I should see the login error {string}
* Given I am on the shop home page
* When I search for {string}
* Then the results title should be {string}
* Then I should see {int} product(s)
* Then I should see the product {string}
* Then I should see the no results message
* When I add these products to the cart:
* Then the cart badge should show {int}
* When I open the cart
* Then the cart should contain:
* When I apply the coupon {string}
* Then the coupon message should be {string}

📊 Step 11: Reports

This config writes two reports on every run:

ReportFolderOpen withBest for
Playwright HTMLplaywright-report/npm run reportEngineers: each Given/When/Then is a step, with traces, screenshots and errors
Cucumber HTMLcucumber-report/index.htmlOpen the file in a browserBusiness readers: features and scenarios as plain Gherkin

playwright-bdd also offers cucumberReporter('json'), 'junit' and 'message', which feed tools such as multiple-cucumber-html-reporter or Jira/Xray. For Allure, follow Integrating Allure Report with Playwright: it works unchanged because these are normal Playwright tests.


🚀 Step 12: Run the BDD Suite in GitHub Actions

CI runs the same npm test command. This is the standard Playwright workflow from Playwright with GitHub Actions, with both reports uploaded. (It was not run on GitHub for this guide; the commands are the ones that passed locally above.)

📄 .github/workflows/bdd.yml

name: BDD tests
on:
  push:
    branches: [ main ]
  pull_request:

jobs:
  bdd:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    env:
      BASE_URL: ${{ vars.BASE_URL }}
      SHOP_USER: ${{ secrets.SHOP_USER }}
      SHOP_PASSWORD: ${{ secrets.SHOP_PASSWORD }}
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: lts/*
      - run: npm ci
      - run: npx playwright install --with-deps chromium
      - run: npm test
      - uses: actions/upload-artifact@v4
        if: ${{ !cancelled() }}
        with:
          name: bdd-reports
          path: |
            playwright-report/
            cucumber-report/
          retention-days: 14
  • retries: process.env.CI ? 2 : 0 in the config means CI retries a failed scenario twice and records a trace on the first retry.
  • Do not commit .features-gen: npm test regenerates it on the runner.

✅ BDD Best Practices That Keep the Framework Maintainable

  • Write behaviour, not clicks. When I log in with the default user survives a UI redesign; When I click the button with id login-btn does not.
  • One behaviour per scenario, ideally 3 to 7 steps. Long scenarios hide what actually failed.
  • Keep steps thin. A step calls one or two Page Object methods or one assertion. Logic lives in pages and helpers.
  • Reuse sentences. Check bddgen export before writing a new step. Ten ways to say “log in” become ten things to maintain.
  • Put assertions only in Then steps, and use web-first assertions (toHaveText, toBeVisible) so they wait automatically.
  • No shared state between scenarios. Each scenario must pass alone and in any order; that is what makes parallel runs safe.
  • Keep secrets out of features. Use steps like the default user that read from environment variables.
  • Use Background only for the true common start, such as opening a page. If some scenarios skip it, it belongs in the scenarios.

💼 Playwright BDD Interview Questions

1. What is the difference between playwright-bdd and Cucumber-JS with Playwright?

With Cucumber-JS, Cucumber is the runner and Playwright is used as a library, so you manage the browser yourself. playwright-bdd generates Playwright Test files from features, so you keep the Playwright runner: fixtures, parallel workers, retries, traces and the HTML report.

2. What does bddgen do, and why must it run before playwright test?

It parses the feature files, matches every step to a step definition and writes test files into .features-gen. Playwright only runs those generated files, so without bddgen it would run stale tests or none at all.

3. How do you share a Page Object between steps without a global variable?

Register the Page Object as a custom fixture with test.extend(), pass that test to createBdd(), and request the fixture in each step’s first argument. Each scenario gets its own instance.

4. When do you use a Scenario Outline instead of a data table?

Use a Scenario Outline when the same scenario should run several times with different data, each run a separate test (for example, several invalid logins). Use a data table when one step needs a list of values inside a single scenario (for example, products to add to one cart).

5. How do you run only smoke tests in a BDD suite?

Tag scenarios with @smoke and run npx playwright test --grep @smoke. You can also generate only matching scenarios with npx bddgen --tags "@smoke".

6. A team writes steps like “When I click #submit”. What is wrong and how would you fix it?

The steps describe implementation, not behaviour, so they break when the UI changes and business readers cannot review them. Rewrite them as behaviour (When I submit the order) and move locators into Page Objects.

7. What happens if a step has no definition?

bddgen fails with “Missing step definitions” and prints a snippet to paste. You can change this with the missingSteps option (for example, 'skip-scenario'), but failing early is the safer default.

Practise more in the Module 10 Framework Design mock interview, which includes BDD, Gherkin and playwright-bdd questions.


📝 Assignment

  1. Easy: Add a scenario to search.feature that searches for mouse and checks that RGB Gaming Mouse is in the results. Done when npm test shows 9 passed.
  2. Medium: Add a Scenario Outline for coupons with an Examples table for SAVE10, FLAT200 and an invalid code, checking the coupon message for each. Done when each row appears as its own test.
  3. Medium: Implement the missing step When I sort products by {string} using the sort-by select, and a Then step that checks the first product price is the lowest. Done when bddgen reports no missing steps.
  4. Stretch: Add a loggedInUser fixture that logs in once through the UI and saves storage state, and use it in a new @account scenario. Done when the scenario passes with --workers=4.

Advertisement

❓ Frequently Asked Questions

🤔 Is playwright-bdd the same as Cucumber?

No. It uses the same Gherkin language and Cucumber expressions, but it runs your scenarios with the Playwright test runner instead of cucumber-js. You do not install @cucumber/cucumber.

🤔 Can I use the Playwright VS Code extension with BDD tests?

Yes. Run npx bddgen first; the generated tests then appear in the Testing panel and can be run and debugged like any Playwright test.

🤔 Should I commit the .features-gen folder?

No. It is regenerated on every run. Commit the feature files, steps and pages, and add .features-gen/ to .gitignore.

🤔 How do I run BDD scenarios in parallel?

Set fullyParallel: true and choose workers in playwright.config.ts. Because every scenario gets its own page and fixtures, scenarios run safely in parallel without extra code.

🤔 Can I use the same steps for API tests?

Yes. Ask for Playwright’s built-in request fixture in a step, for example Given('the API is up', async ({ request }) => { ... }), and mix UI and API steps in one scenario.


🏁 Summary

  • playwright-bdd generates Playwright tests from Gherkin, so you keep fixtures, parallel runs, traces and reports.
  • defineBddConfig() sets the features and steps; npm test runs bddgen then playwright test.
  • Page Objects become fixtures, and createBdd(test) gives typed Given/When/Then that request them by name.
  • Scenario Outlines run one scenario per data row; data tables pass lists into a single step.
  • Tags filter runs with --grep, hooks run around scenarios, and missing steps fail fast with a ready snippet.

Next, put this framework into a bigger picture in Real-World Enterprise Playwright Framework Implementation.

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in