Objects are the backbone of test automation: login credentials, form data, API payloads and even your Playwright config are all objects. In this beginner-friendly guide you will learn how TypeScript objects work, how to give them types, and how to use them in real Playwright tests.
📖 What You’ll Learn: object types, type aliases, optional and readonly properties, index signatures and Record, nested objects, arrays of objects, looping, destructuring, merging, comparing objects, and objects in Playwright tests.
🧱 What Is an Object in TypeScript?
An object is a way to group related values together under one name. Instead of creating five separate variables for a user’s name, email, password, role and age, you put them in one object. Each value is stored as a property: a key (the name) and a value.
In plain JavaScript, objects can hold anything and you only find mistakes when the code runs. TypeScript adds types to objects, so your editor warns you the moment you misspell a property or put a number where a string belongs. For test automation this matters a lot, because most test data, such as login users, form inputs and API payloads, is stored in objects.
// A simple object: TypeScript infers the type automatically
const user = {
name: 'Deepesh',
email: 'deepesh@sqatools.in',
age: 30,
isActive: true,
};
console.log(user.name); // Deepesh
console.log(user['email']); // deepesh@sqatools.in (bracket notation)
📝 Note: When you hover over user in VS Code, TypeScript shows the inferred type { name: string; email: string; age: number; isActive: boolean }. You did not write it, but TypeScript still protects you.
✍️ Declaring an Object Type
You can describe the shape of an object explicitly. This is called an object type annotation. It lists every property and its type, separated by semicolons.
let loginUser: { username: string; password: string; rememberMe: boolean };
loginUser = {
username: 'standard_user',
password: 'secret_sauce',
rememberMe: false,
};
// ❌ Error: Property 'rememberMe' is missing
// loginUser = { username: 'admin', password: '1234' };
// ❌ Error: Type 'number' is not assignable to type 'string'
// loginUser = { username: 101, password: 'x', rememberMe: true };
Writing the shape inline works, but it gets repetitive. In real projects you give the shape a name with a type alias (or an interface) and reuse it everywhere.
type User = {
username: string;
password: string;
role: string;
};
const admin: User = { username: 'admin', password: 'Admin@123', role: 'admin' };
const guest: User = { username: 'guest', password: 'Guest@123', role: 'viewer' };
❓ Optional and Readonly Properties
Not every property is always present. Add a ? after the name to make it optional. Add readonly in front to stop anyone from changing it after the object is created.
type TestConfig = {
readonly baseUrl: string; // cannot be changed later
browser: string;
headless?: boolean; // optional
retries?: number; // optional
};
const config: TestConfig = {
baseUrl: 'https://sqatools.in',
browser: 'chromium',
};
config.browser = 'firefox'; // ✅ allowed
// config.baseUrl = 'https://x.com'; // ❌ Error: read-only property
// Optional values may be undefined, so give a fallback
const retries = config.retries ?? 0;
💡 Tip: Use readonly for values like URLs and environment names that should never change during a test run. It prevents accidental overwrites in shared test data.
🔧 Adding, Updating and Deleting Properties
TypeScript only lets you use properties that exist in the type. This is a feature: it catches typos like usernmae immediately.
type Product = { name: string; price: number; inStock?: boolean };
const product: Product = { name: 'Laptop', price: 55000 };
product.price = 52000; // ✅ update
product.inStock = true; // ✅ add an optional property
delete product.inStock; // ✅ delete works only on optional properties
// product.color = 'black'; // ❌ Error: 'color' does not exist on type 'Product'
If you genuinely need an object whose keys are not known in advance (for example, HTTP headers), use an index signature or the built-in Record type.
// Any string key, every value is a string
const headers: { [key: string]: string } = {};
headers['Content-Type'] = 'application/json';
headers['Authorization'] = 'Bearer token123';
// Same thing using Record<KeyType, ValueType>
const statusMessages: Record<number, string> = {
200: 'OK',
404: 'Not Found',
500: 'Server Error',
};
🪆 Nested Objects
Objects can contain other objects. This is common for API responses and page configuration.
⚠️ Common mistake: Accessing a property of something that may be undefined crashes at runtime. Use optional chaining ?. to read safely, as in customer.contacts.phone?.length.
📋 Arrays of Objects
An array of objects is the most common way to store test data for data-driven tests. Each object is one test case.
Destructuring pulls properties out into variables. The spread operator... copies properties into a new object, which is the easiest way to merge or override values.
⚠️ Common mistake: Spread makes a shallow copy. Nested objects are still shared between the copy and the original. For a deep copy use structuredClone(obj).
⚖️ Comparing Objects
Two objects are only === equal if they are the same object in memory, even if their contents match. To compare contents, compare the values or use a deep equality check.
const a = { id: 1, name: 'Test' };
const b = { id: 1, name: 'Test' };
console.log(a === b); // false: different objects
console.log(JSON.stringify(a) === JSON.stringify(b)); // true (simple objects, same key order)
In Playwright tests you do not need any of this: expect(actual).toEqual(expected) performs a deep comparison for you.
🎭 Objects in Playwright: Real Examples
Objects are everywhere in Playwright. The config file is an object, test data is usually objects, and API requests send objects as JSON.
const cases = [
{ username: 'locked_out_user', error: 'Sorry, this user has been locked out.' },
{ username: 'unknown_user', error: 'Username and password do not match' },
];
for (const c of cases) {
test('shows error for ' + c.username, async ({ page }) => {
await page.goto('https://www.saucedemo.com/');
await page.getByPlaceholder('Username').fill(c.username);
await page.getByPlaceholder('Password').fill('secret_sauce');
await page.getByRole('button', { name: 'Login' }).click();
await expect(page.locator('[data-test="error"]')).toContainText(c.error);
});
}
3. Sending and checking an object in an API test
test('create a post via API', async ({ request }) => {
const payload = { title: 'Playwright', body: 'Objects in TypeScript', userId: 1 };
const response = await request.post('https://jsonplaceholder.typicode.com/posts', { data: payload });
expect(response.status()).toBe(201);
const body = await response.json();
expect(body).toMatchObject(payload); // deep, partial object comparison
});
✅ Best Practices
Give every reusable object shape a name with type or interface instead of repeating inline types.
Mark values that must not change as readonly.
Use optional properties ? only when a value can truly be missing, and handle undefined with ?? or ?..
Keep test data objects in a separate file (for example test-data/users.ts) so tests stay short.
Prefer toEqual or toMatchObject in Playwright assertions to compare objects.
❓ FAQ
🤔 What is the difference between an object type and an interface in TypeScript?
Both describe the shape of an object and are often interchangeable. Interfaces can be extended and merged, while type aliases can also describe unions and primitives. Read the full comparison in TypeScript Interfaces.
🤔 How do I define an array of objects in TypeScript?
Create a type for one item, then add []: type User = { name: string }; const users: User[] = [];. You can also write Array<User>.
🤔 How do I merge two objects in TypeScript?
Use the spread operator: const merged = { ...first, ...second };. Properties in second overwrite the same properties in first.
🤔 How do I make an object property optional?
Add a question mark after the property name, for example phone?: string. Its value can then be a string or undefined.
🤔 Why does TypeScript say “Property does not exist on type”?
You are using a property that is not part of the object’s type, usually because of a typo or a missing field in the type. Add it to the type (optionally with ?) or fix the spelling.
Arrays are everywhere in test automation — storing test data, collecting page elements, managing results. TypeScript arrays come with strong typing that catches bugs before your tests even run. This guide covers everything from basics to advanced patterns with Playwright examples.
📖 What You’ll Learn: Array types, push/pop/splice, map/filter/reduce, spread operator, tuples, readonly arrays, and array operations in Playwright tests.
📦 Declaring Arrays
// Two ways to declare typed arrays
let browsers: string[] = ['chromium', 'firefox', 'webkit'];
let scores: Array<number> = [85, 92, 78, 95];
// Mixed types with union
let mixed: (string | number)[] = ['hello', 42, 'world'];
// Empty array with type
let results: boolean[] = [];
// Array of objects
let users: { name: string; role: string }[] = [
{ name: 'Deepesh', role: 'SDET' },
{ name: 'John', role: 'QA Lead' },
];
// 2D array (matrix)
let grid: number[][] = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
➕ Adding & Removing Elements
let fruits: string[] = ['apple', 'banana'];
// Add to end
fruits.push('cherry'); // ['apple', 'banana', 'cherry']
// Add to beginning
fruits.unshift('mango'); // ['mango', 'apple', 'banana', 'cherry']
// Remove from end
let last = fruits.pop(); // 'cherry', array: ['mango', 'apple', 'banana']
// Remove from beginning
let first = fruits.shift(); // 'mango', array: ['apple', 'banana']
// Remove/insert at position with splice
let colors: string[] = ['red', 'green', 'blue', 'yellow'];
colors.splice(1, 2); // Remove 2 items from index 1 → ['red', 'yellow']
colors.splice(1, 0, 'purple'); // Insert at index 1 → ['red', 'purple', 'yellow']
// Find index and remove
let items = ['a', 'b', 'c', 'd'];
let idx = items.indexOf('c');
if (idx !== -1) items.splice(idx, 1); // ['a', 'b', 'd']
🔍 Searching & Checking Arrays
let numbers: number[] = [10, 20, 30, 40, 50];
// includes — does it contain a value?
console.log(numbers.includes(30)); // true
// indexOf — find position (-1 if not found)
console.log(numbers.indexOf(40)); // 3
// find — first element matching condition
let found = numbers.find(n => n > 25);
console.log(found); // 30
// findIndex — index of first match
let foundIdx = numbers.findIndex(n => n > 25);
console.log(foundIdx); // 2
// every — do ALL elements match?
let allPositive = numbers.every(n => n > 0); // true
// some — does ANY element match?
let hasLarge = numbers.some(n => n > 100); // false
🔄 map, filter & reduce
let prices: number[] = [100, 200, 300, 400, 500];
// map — transform each element
let discounted = prices.map(p => p * 0.9);
console.log(discounted); // [90, 180, 270, 360, 450]
// filter — keep elements matching condition
let expensive = prices.filter(p => p >= 300);
console.log(expensive); // [300, 400, 500]
// reduce — combine all elements into one value
let total = prices.reduce((sum, p) => sum + p, 0);
console.log(total); // 1500
// Chaining — filter + map + reduce
let premiumTotal = prices
.filter(p => p >= 300) // [300, 400, 500]
.map(p => p * 1.1) // [330, 440, 550]
.reduce((sum, p) => sum + p, 0); // 1320
console.log(premiumTotal);
// flat — flatten nested arrays
let nested: number[][] = [[1, 2], [3, 4], [5]];
let flat = nested.flat();
console.log(flat); // [1, 2, 3, 4, 5]
💡 map transforms, filter selects, reduce combines. Chain them together for powerful data pipelines. These are the three most important array methods to master.
import { test, expect } from '@playwright/test';
test('collect and verify all product names', async ({ page }) => {
await page.goto('https://sqatools.in');
// Collect all text content into an array
const links = page.locator('nav a');
const texts: string[] = await links.allTextContents();
console.log('Navigation links:', texts);
expect(texts.length).toBeGreaterThan(0);
// Filter only links containing 'Playwright'
const playwrightLinks = texts.filter(t => t.toLowerCase().includes('playwright'));
console.log('Playwright links:', playwrightLinks);
});
// Data-driven testing with arrays
const testData: [string, string, boolean][] = [
['admin@test.com', 'admin123', true],
['invalid@test.com', 'wrong', false],
['', '', false],
];
for (const [email, password, shouldPass] of testData) {
test(`login with ${email || 'empty'} should ${shouldPass ? 'pass' : 'fail'}`, async ({ page }) => {
await page.goto('/login');
await page.fill('#email', email);
await page.fill('#password', password);
await page.click('#submit');
if (shouldPass) {
await expect(page.locator('.dashboard')).toBeVisible();
} else {
await expect(page.locator('.error')).toBeVisible();
}
});
}
❓ FAQ
🤔 What is the difference between string[] and Array<string>?
They are identical — both declare an array of strings. string[] is shorter and more commonly used. Array<string> is clearer for complex types like Array<Map<string, number>>.
🤔 How do I get all text from Playwright locators into an array?
Use await locator.allTextContents() — it returns a string[] with the text content of every matching element. For inner text, use allInnerTexts().
Functions are the building blocks of clean, reusable code. In test automation, you’ll use them everywhere — from page actions to custom assertions to utility helpers. This guide covers every function pattern in TypeScript with real Playwright examples.
📖 What You’ll Learn: Function declarations, arrow functions, optional & default parameters, rest parameters, return types, overloads, generics in functions, and async functions in Playwright.
🔧 Function Declarations & Expressions
// Function declaration
function greet(name: string): string {
return `Hello, ${name}!`;
}
// Function expression
const add = function(a: number, b: number): number {
return a + b;
};
// Arrow function (most common in modern TypeScript)
const multiply = (a: number, b: number): number => a * b;
// Void function — returns nothing
function logMessage(msg: string): void {
console.log(`[LOG]: ${msg}`);
}
console.log(greet('QA Engineer')); // Hello, QA Engineer!
console.log(add(5, 3)); // 8
console.log(multiply(4, 7)); // 28
// Type alias for a function
type Validator = (value: string) => boolean;
const isEmail: Validator = (value) => value.includes('@');
const isNotEmpty: Validator = (value) => value.trim().length > 0;
console.log(isEmail('test@test.com')); // true
console.log(isNotEmpty('')); // false
// Callback functions
function runValidation(input: string, validator: Validator, onResult: (passed: boolean) => void): void {
const result = validator(input);
onResult(result);
}
runValidation('hello@test.com', isEmail, (passed) => {
console.log(passed ? '✅ Valid' : '❌ Invalid');
});
// Returning functions (higher-order)
function createMultiplier(factor: number): (n: number) => number {
return (n) => n * factor;
}
const double = createMultiplier(2);
const triple = createMultiplier(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15
🧬 Generic Functions
// Generic function — works with any type
function firstElement<T>(arr: T[]): T | undefined {
return arr[0];
}
console.log(firstElement([1, 2, 3])); // 1 (type: number)
console.log(firstElement(['a', 'b', 'c'])); // 'a' (type: string)
// Generic with constraint
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { name: 'Deepesh', role: 'SDET' };
console.log(getProperty(user, 'name')); // 'Deepesh'
// Generic async function
async function fetchData<T>(url: string): Promise<T> {
const response = await fetch(url);
return response.json() as Promise<T>;
}
💡 Generics let you write ONE function that works with strings, numbers, objects — anything. TypeScript figures out the type automatically when you call it.
⚡ Async Functions
// Async function returns a Promise
async function fetchTitle(url: string): Promise<string> {
const response = await fetch(url);
const html = await response.text();
const match = html.match(/<title>(.*)<\/title>/);
return match ? match[1] : 'No title found';
}
// Async arrow function
const delay = async (ms: number): Promise<void> => {
return new Promise(resolve => setTimeout(resolve, ms));
};
// Try-catch in async functions
async function safeRequest(url: string): Promise<string | null> {
try {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.text();
} catch (error) {
console.error('Request failed:', error);
return null;
}
}
🎭 Functions in Playwright — Real Examples
import { test, expect, Page } from '@playwright/test';
// Reusable login helper function
async function login(page: Page, email: string, password: string): Promise<void> {
await page.goto('/login');
await page.fill('#email', email);
await page.fill('#password', password);
await page.click('#login-btn');
await expect(page.locator('.dashboard')).toBeVisible();
}
// Retry function for flaky operations
async function retry<T>(fn: () => Promise<T>, maxAttempts: number = 3): Promise<T> {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await fn();
} catch (error) {
if (attempt === maxAttempts) throw error;
console.log(`Attempt ${attempt} failed, retrying...`);
await new Promise(r => setTimeout(r, 1000));
}
}
throw new Error('Should not reach here');
}
// Using helper functions in tests
test('login and verify dashboard', async ({ page }) => {
await login(page, 'admin@sqatools.in', 'test123');
await expect(page).toHaveTitle(/Dashboard/);
});
test('retry flaky element click', async ({ page }) => {
await page.goto('https://sqatools.in');
await retry(async () => {
await page.click('.dynamic-button');
await expect(page.locator('.result')).toBeVisible();
});
});
❓ FAQ
🤔 When should I use arrow functions vs regular functions?
Use arrow functions for callbacks, short expressions, and class methods. Use regular functions when you need hoisting or a named function in stack traces. In Playwright, arrow functions are standard for test callbacks and helpers.
🤔 What is the difference between optional and default parameters?
Optional parameters (name?: string) can be omitted and will be undefined. Default parameters (name: string = 'Guest') have a fallback value when omitted. Default parameters are preferred when you have a sensible default.
Loops let you repeat actions — whether it’s iterating through test data, checking multiple elements, or retrying flaky operations. This guide covers every loop type in TypeScript with real Playwright examples you’ll use daily in test automation.
📖 What You’ll Learn: for loop, while loop, do…while, for…of, for…in, forEach, break/continue, and looping through Playwright elements.
🔁 for Loop
The classic loop — you control the start, end, and step.
// Basic for loop
for (let i: number = 0; i < 5; i++) {
console.log('Iteration:', i);
}
// Output: 0, 1, 2, 3, 4
// Counting backwards
for (let i: number = 10; i > 0; i -= 2) {
console.log(i);
}
// Output: 10, 8, 6, 4, 2
// Looping through an array by index
let browsers: string[] = ['chromium', 'firefox', 'webkit'];
for (let i = 0; i < browsers.length; i++) {
console.log(`Browser ${i + 1}: ${browsers[i]}`);
}
🔄 while and do...while Loops
// while — checks condition BEFORE each iteration
let attempts: number = 0;
while (attempts < 3) {
console.log(`Attempt ${attempts + 1}`);
attempts++;
}
// do...while — runs at least ONCE, then checks condition
let input: string = '';
do {
input = 'valid'; // simulating user input
console.log('Processing input:', input);
} while (input === '');
// Retry pattern (common in test automation)
let retryCount: number = 0;
let success: boolean = false;
while (!success && retryCount < 3) {
try {
// attempt some operation
success = true;
console.log('Operation succeeded!');
} catch {
retryCount++;
console.log(`Retry ${retryCount}/3`);
}
}
⚠️ Always include a way to exit while loops (increment a counter, set a flag). An infinite loop will crash your tests!
🎯 for...of and for...in Loops
// for...of — iterate over VALUES (arrays, strings, maps)
let testCases: string[] = ['login', 'signup', 'checkout'];
for (const tc of testCases) {
console.log('Running test:', tc);
}
// for...in — iterate over KEYS/INDICES (objects)
let config = { baseURL: 'https://sqatools.in', timeout: 30000, retries: 2 };
for (const key in config) {
console.log(`${key}: ${config[key as keyof typeof config]}`);
}
// Iterating over a Map
let testData = new Map();
testData.set('user1', 'admin@test.com');
testData.set('user2', 'user@test.com');
for (const [key, value] of testData) {
console.log(`${key} -> ${value}`);
}
💡 Quick Rule: Use for...of for arrays and iterable values. Use for...in for object keys. Never use for...in on arrays — it iterates over indices as strings, which causes bugs.
📋 forEach and Array Methods
let scores: number[] = [85, 92, 78, 95, 88];
// forEach — run a function for each element
scores.forEach((score, index) => {
console.log(`Student ${index + 1}: ${score}`);
});
// map — transform each element into a new array
let grades = scores.map(s => s >= 90 ? 'A' : s >= 80 ? 'B' : 'C');
console.log(grades); // ['B', 'A', 'C', 'A', 'B']
// filter — keep only elements that match
let topScores = scores.filter(s => s >= 90);
console.log(topScores); // [92, 95]
// find — get the first match
let firstTop = scores.find(s => s >= 90);
console.log(firstTop); // 92
// every/some — check all or any
let allPassed = scores.every(s => s >= 60); // true
let anyPerfect = scores.some(s => s === 100); // false
⏹️ break and continue
// break — exit the loop entirely
for (let i = 0; i < 10; i++) {
if (i === 5) break;
console.log(i);
}
// Output: 0, 1, 2, 3, 4
// continue — skip current iteration, go to next
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) continue; // skip even numbers
console.log(i);
}
// Output: 1, 3, 5, 7, 9
🎭 Loops in Playwright — Real Examples
import { test, expect } from '@playwright/test';
test('iterate through page elements', async ({ page }) => {
await page.goto('https://sqatools.in');
// Get all navigation links and verify each one
const navLinks = page.locator('nav a');
const count = await navLinks.count();
for (let i = 0; i < count; i++) {
const text = await navLinks.nth(i).textContent();
const href = await navLinks.nth(i).getAttribute('href');
console.log(`Link ${i + 1}: ${text} -> ${href}`);
expect(href).not.toBeNull();
}
});
// Data-driven test with for...of
const testUsers = [
{ email: 'admin@test.com', role: 'admin' },
{ email: 'user@test.com', role: 'user' },
{ email: 'guest@test.com', role: 'guest' },
];
for (const user of testUsers) {
test(`login as ${user.role}`, async ({ page }) => {
await page.goto('/login');
await page.fill('#email', user.email);
await page.fill('#password', 'test123');
await page.click('#login-btn');
await expect(page.locator('.role-badge')).toHaveText(user.role);
});
}
❓ FAQ
🤔 What is the difference between for...of and for...in?
for...of iterates over values (arrays, strings). for...in iterates over keys/indices (objects). Use for...of for arrays and for...in for object properties.
🤔 How do I loop through Playwright locators?
Use locator.count() to get the number of matches, then use a for loop with locator.nth(i) to access each element individually.
Conditions let you control which code runs based on different scenarios — essential for building smart Playwright tests that handle popups, dynamic content, and different environments. This guide covers if/else, switch, ternary operators, and type guards with real test automation examples.
📖 What You’ll Learn: if/else statements, else if chains, switch/case, ternary operator, type narrowing with conditions, and real Playwright conditional flows.
🔀 if / else Statement
The most basic conditional — execute code only when a condition is true.
let temperature: number = 30;
if (temperature > 25) {
console.log("It's hot outside! ☀️");
} else {
console.log("It's cool outside! 🌤️");
}
// Output: "It's hot outside! ☀️"
🔗 else if Chain
Check multiple conditions in sequence — the first match wins.
let score: number = 85;
let grade: string;
if (score >= 90) {
grade = "A — Excellent!";
} else if (score >= 80) {
grade = "B — Good job!";
} else if (score >= 70) {
grade = "C — Average";
} else if (score >= 60) {
grade = "D — Below average";
} else {
grade = "F — Needs improvement";
}
console.log(grade); // "B — Good job!"
💡 Tip: Order your conditions from most specific to least specific. TypeScript evaluates them top-to-bottom and stops at the first match.
🔄 Switch Statement
When you have many possible values for a single variable, switch is cleaner than multiple if/else statements.
type Browser = 'chromium' | 'firefox' | 'webkit';
let browserName: Browser = 'chromium';
switch (browserName) {
case 'chromium':
console.log('🌐 Running on Chrome/Edge');
break;
case 'firefox':
console.log('🦊 Running on Firefox');
break;
case 'webkit':
console.log('🧭 Running on Safari');
break;
default:
console.log('❓ Unknown browser');
}
// Switch with return (in a function)
function getTimeout(env: string): number {
switch (env) {
case 'production': return 30000;
case 'staging': return 15000;
case 'local': return 5000;
default: return 10000;
}
}
⚡ Ternary Operator
A one-liner alternative to if/else — perfect for simple conditions.
// Syntax: condition ? valueIfTrue : valueIfFalse
let isProduction: boolean = false;
let baseURL = isProduction ? 'https://app.com' : 'https://staging.app.com';
let userAge: number = 20;
let category = userAge >= 18 ? 'Adult' : 'Minor';
// Nested ternary (use sparingly!)
let speed: number = 100;
let zone = speed > 120 ? 'Danger' : speed > 80 ? 'Fast' : 'Normal';
⚠️ Avoid nested ternaries — they’re hard to read. Use if/else instead when the logic is complex.
🔍 Type Narrowing with Conditions
TypeScript gets smarter inside conditional blocks — it narrows the type automatically.
// typeof narrowing
function formatValue(value: string | number): string {
if (typeof value === 'string') {
return value.toUpperCase(); // TypeScript knows it's a string here
} else {
return value.toFixed(2); // TypeScript knows it's a number here
}
}
// Truthiness narrowing
function greetUser(name: string | null | undefined): string {
if (name) {
return 'Hello, ' + name; // name is definitely a string here
}
return 'Hello, Guest';
}
// in operator narrowing
interface Dog { bark(): void; breed: string; }
interface Cat { meow(): void; color: string; }
function handlePet(pet: Dog | Cat) {
if ('bark' in pet) {
pet.bark(); // TypeScript knows it's a Dog
} else {
pet.meow(); // TypeScript knows it's a Cat
}
}
🎭 Conditions in Playwright — Real Examples
import { test, expect } from '@playwright/test';
test('handle dynamic page content', async ({ page }) => {
await page.goto('https://sqatools.in');
// Close popup if it appears
const popup = page.locator('.popup-overlay');
if (await popup.isVisible({ timeout: 3000 }).catch(() => false)) {
await popup.locator('.close-btn').click();
console.log('Popup closed');
}
// Environment-based navigation
const env = process.env.TEST_ENV ?? 'staging';
switch (env) {
case 'production':
await page.goto('https://sqatools.in');
break;
case 'staging':
await page.goto('https://staging.sqatools.in');
break;
default:
await page.goto('http://localhost:3000');
}
// Conditional assertions based on page state
const loginBtn = page.locator('#login-btn');
const dashboardLink = page.locator('#dashboard');
if (await loginBtn.isVisible()) {
console.log('User is not logged in');
await loginBtn.click();
} else if (await dashboardLink.isVisible()) {
console.log('User is already logged in');
}
});
❓ FAQ
🤔 When should I use switch vs if/else?
Use switch when comparing a single variable against multiple specific values. Use if/else when conditions are complex expressions or involve multiple variables.
🤔 What is type narrowing in TypeScript?
Type narrowing is when TypeScript automatically narrows a union type to a more specific type inside a conditional block. For example, after if (typeof x === 'string'), TypeScript knows x is a string.
Operators are the building blocks of every TypeScript program. Whether you’re writing Playwright test automation or building applications, understanding operators is essential. This guide covers every operator type in TypeScript with practical examples you can use in your Playwright projects.
📖 What You’ll Learn: Arithmetic, Comparison, Logical, Assignment, Ternary, Nullish Coalescing, and Type operators — all with real Playwright examples.
➕ Arithmetic Operators
Arithmetic operators perform mathematical calculations on numbers.
Comparison operators compare two values and return a boolean (true or false). These are essential in Playwright assertions.
let x: number = 5;
let y: string = "5";
// Loose equality (compares value only, allows type coercion)
console.log(x == y); // true — NOT recommended in TypeScript
// Strict equality (compares value AND type)
console.log(x === 5); // true — ALWAYS use this
console.log(x === y); // Error! TypeScript catches this at compile time
// Not equal
console.log(x != y); // false (loose)
console.log(x !== 10); // true (strict)
// Greater / Less than
console.log(x > 3); // true
console.log(x >= 5); // true
console.log(x < 10); // true
console.log(x <= 4); // false
⚠️ Golden Rule: Always use === (strict equality) and !== in TypeScript. The loose operators == and != can cause subtle bugs that are hard to debug in test automation.
🧠 Logical Operators
Logical operators combine multiple conditions. You'll use these constantly in test automation for complex validations.
let isLoggedIn: boolean = true;
let isAdmin: boolean = false;
let hasPermission: boolean = true;
// AND (&&) — ALL conditions must be true
console.log(isLoggedIn && isAdmin); // false
console.log(isLoggedIn && hasPermission); // true
// OR (||) — at least ONE must be true
console.log(isAdmin || hasPermission); // true
// NOT (!) — reverses the boolean
console.log(!isLoggedIn); // false
console.log(!isAdmin); // true
// Combining multiple operators
if (isLoggedIn && (isAdmin || hasPermission)) {
console.log("Access granted"); // This runs
}
📝 Assignment Operators
let num: number = 10;
num += 5; // num = num + 5 → 15
num -= 3; // num = num - 3 → 12
num *= 2; // num = num * 2 → 24
num /= 4; // num = num / 4 → 6
num %= 4; // num = num % 4 → 2
num **= 3; // num = num ** 3 → 8
❓ Ternary & Nullish Coalescing Operators
These are shorthand operators that make your code cleaner and more readable.
// Ternary Operator: condition ? valueIfTrue : valueIfFalse
let age: number = 20;
let status: string = age >= 18 ? "Adult" : "Minor";
console.log(status); // "Adult"
// Nullish Coalescing (??) — returns right side if left is null/undefined
let username: string | null = null;
let displayName = username ?? "Guest";
console.log(displayName); // "Guest"
// Optional Chaining (?.) — safely access nested properties
interface User {
name: string;
address?: { city?: string };
}
let user: User = { name: "Deepesh" };
console.log(user.address?.city); // undefined (no error!)
🔍 Type Operators (TypeScript-Specific)
// typeof — check runtime type
let value: unknown = "hello";
if (typeof value === "string") {
console.log(value.toUpperCase()); // "HELLO"
}
// instanceof — check if object is an instance of a class
class Animal { name: string = "dog"; }
class Dog extends Animal { breed: string = "lab"; }
let pet = new Dog();
console.log(pet instanceof Dog); // true
console.log(pet instanceof Animal); // true
// keyof — get union of object keys (compile-time only)
interface Config {
baseURL: string;
timeout: number;
}
type ConfigKey = keyof Config; // "baseURL" | "timeout"
// as — type assertion
let someValue: unknown = "this is a string";
let strLength: number = (someValue as string).length;
🤔 What is the difference between == and === in TypeScript?
== compares values with type coercion (loose equality), while === compares both value and type (strict equality). Always use === in TypeScript.
🤔 What is the nullish coalescing operator (??) in TypeScript?
The ?? operator returns the right-hand value when the left-hand value is null or undefined. Unlike ||, it doesn't treat 0, "", or false as "empty".
🤔 How do I use typeof in Playwright tests?
Use typeof to check the runtime type of values returned from page methods. For example, typeof (await page.title()) === 'string' ensures you're working with a string before calling string methods.
🎯 Next Steps
Now that you understand TypeScript operators, continue your learning journey:
Passkeys are replacing passwords across the web, and if your test automation framework can’t handle WebAuthn flows, you’re already falling behind. Playwright 1.61 introduced browserContext.credentials — a virtual authenticator that lets you register, store, and use passkeys entirely in code. This guide walks you through everything you need to automate passkey login testing, with ready-to-use TypeScript examples.
🔐 What Is WebAuthn and Why Should QA Engineers Care?
WebAuthn (Web Authentication) is the W3C standard behind passkeys. Instead of passwords, users authenticate with biometrics (fingerprint, face recognition) or hardware security keys.
Major platforms — Google, Apple, Microsoft, and most modern SaaS products — now support passkey login. As a QA engineer or SDET, you’ll increasingly encounter apps that use WebAuthn, and your automation framework needs to test these flows reliably.
⚠️ The Problem: Traditional test tools couldn’t interact with hardware authenticators. You’d have to skip those tests or test them manually. Playwright 1.61 solves this completely with a built-in virtual authenticator!
📋 Prerequisites
Before we start, make sure you have:
✅ Node.js 18 or later
✅ Playwright 1.61+ installed
✅ Basic knowledge of TypeScript and Playwright
# Install or upgrade Playwright
npm install @playwright/test@latest
npx playwright install
# Verify version
npx playwright --version
⚙️ Setting Up the Virtual Authenticator
Playwright’s virtual authenticator is available through browserContext.credentials. No additional setup is required — it’s built into the browser context.
import { test, expect } from '@playwright/test';
test('virtual authenticator is available', async ({ context }) => {
// The credentials API is ready to use immediately
const credentials = await context.credentials.list();
expect(credentials).toEqual([]);
console.log('Virtual authenticator is active!');
});
💡 Key Insight: The virtual authenticator behaves like a FIDO2-compliant security key. When a website triggers a WebAuthn ceremony (registration or login), Playwright’s authenticator responds automatically — no user interaction needed!
🔑 Registering a Passkey in Your Tests
Here’s how to automate passkey registration:
import { test, expect } from '@playwright/test';
test('register a new passkey', async ({ context, page }) => {
// Navigate to your app's registration page
await page.goto('https://your-app.com/settings/security');
// Click the "Add Passkey" button
await page.getByRole('button', { name: 'Add Passkey' }).click();
// Playwright's virtual authenticator handles the WebAuthn ceremony
// Wait for confirmation
await expect(page.getByText('Passkey added successfully')).toBeVisible();
// Verify the credential was stored
const credentials = await context.credentials.list();
expect(credentials.length).toBe(1);
console.log('Credential ID:', credentials[0].id);
});
When the browser triggers navigator.credentials.create(), the virtual authenticator generates a key pair and responds with the public key credential — exactly as a real hardware key would.
🚀 Automating Passkey Login
Once a passkey is registered, testing the login flow is straightforward:
test('login with passkey', async ({ context, page }) => {
// Step 1: Register a passkey
await page.goto('https://your-app.com/register');
await page.getByRole('button', { name: 'Register with Passkey' }).click();
await expect(page.getByText('Passkey registered')).toBeVisible();
// Step 2: Navigate to login
await page.goto('https://your-app.com/login');
// Step 3: Sign in with passkey
await page.getByRole('button', { name: 'Sign in with Passkey' }).click();
// The virtual authenticator uses the stored credential
await expect(page.getByText('Welcome back')).toBeVisible();
await expect(page).toHaveURL(/dashboard/);
});
✅ No mocking, no bypassing — you’re testing the REAL WebAuthn implementation end to end. This is the biggest advantage over traditional approaches!
♻️ Reusing Credentials Across Tests with Storage State
Registering a passkey in every test is wasteful. Use Playwright’s storage state to authenticate once and reuse:
// auth.setup.ts
import { test as setup } from '@playwright/test';
setup('register and authenticate with passkey', async ({ context, page }) => {
await page.goto('https://your-app.com/register');
await page.getByRole('button', { name: 'Register with Passkey' }).click();
await expect(page.getByText('Passkey registered')).toBeVisible();
// Save authenticated state
await context.storageState({ path: '.auth/passkey-user.json' });
});
❌ Mistake 1: Credentials don’t persist across browser contexts.
Each browserContext has its own virtual authenticator. If your test creates a new context, previously registered passkeys won’t be available. Solution: register and login within the same context, or use storage state.
❌ Mistake 2: Not waiting for the WebAuthn ceremony to complete.
The registration and authentication ceremonies are asynchronous. Clicking the next button before the ceremony finishes causes flaky tests. Always wait for a visible confirmation element.
❌ Mistake 3: Forgetting to await credentials API calls.
context.credentials.list() returns a Promise. Missing await leads to empty results and confusing test failures.
❓ FAQ
🤔 Can I test passkeys without a real WebAuthn-enabled app?
🤔 Does Playwright’s virtual authenticator work with all browsers?
The virtual authenticator works with Chromium-based browsers. Firefox and WebKit support may vary — check the Playwright 1.61 release notes for the latest compatibility.
🤔 Can I export and import passkey credentials between test runs?
Yes, context.credentials.list() returns credential objects that can be serialized. However, using storage state (shown above) is the recommended approach for persisting authenticated sessions.
🤔 What’s the difference between passkeys and FIDO2 security keys?
Passkeys are discoverable FIDO2 credentials synced across devices (through iCloud Keychain, Google Password Manager, etc.). Hardware security keys are physical devices. Playwright’s virtual authenticator simulates both.
🤔 Do I need to modify my app’s code to test with the virtual authenticator?
No. The virtual authenticator intercepts standard WebAuthn API calls at the browser level. Your app’s code doesn’t need any changes.
🎯 Next Steps
Now that you can automate passkey testing, try these:
🔧 Add passkey tests to your CI/CD pipeline
🧪 Test error scenarios (expired credentials, wrong authenticator)
📐 Combine passkey auth with your existing Page Object Model — see our Playwright POM tutorial
💾 Explore the new page.localStorage and page.sessionStorage APIs in Playwright 1.61
🎬 Want to see this in action? Watch the full video tutorial!
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.
📖 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.
Topic
Cucumber-JS + Playwright library
playwright-bdd + Playwright Test
Test runner
cucumber-js
Playwright Test (npx playwright test)
Browser and page setup
You write BeforeAll / Before hooks
Built-in page fixture, cleaned up automatically
Page Objects
Created in the World or in steps
Injected into steps as fixtures
Parallel runs
--parallel, shared state is risky
Playwright workers, fullyParallel, sharding
Traces, screenshots, video
Manual
trace / screenshot options in the config
Reports
Cucumber formatters
Playwright HTML report and Cucumber reports
Run one test in the IDE
Needs a Cucumber plugin
Works 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/test1.65.1, playwright-bdd9.2.1, typescript 7.0.2.
@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.
⚠️ 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. |
Keyword
Meaning
Feature
The feature under test, plus an optional user story (As a / I want / So that).
Background
Steps that run before every scenario in this file, like beforeEach.
Scenario
One example of behaviour. Becomes one Playwright test.
Given / When / Then
Context, action, expected outcome. And and But continue the previous type.
Scenario Outline + Examples
One scenario run once per table row. <username> is replaced with the row value.
@smoke, @login
Tags. 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.)
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.
🧩 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.
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 expression
Matches
Value passed in
{string}
"testuser" or 'testuser'
testuser (string, without quotes)
{int}
2
2 (number)
{float}
4.5
4.5 (number)
product(s)
product or products
nothing (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.
> 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):
// 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.
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."
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.
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:
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.
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)
Goal
Command
Smoke scenarios only
npx playwright test --grep @smoke
Everything except cart
npx playwright test --grep-invert @cart
Generate only some scenarios
npx bddgen --tags "@login and not @slow"
One feature file
npx playwright test .features-gen/features/login.feature.spec.js
Watch it run
npx 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:
Report
Folder
Open with
Best for
Playwright HTML
playwright-report/
npm run report
Engineers: each Given/When/Then is a step, with traces, screenshots and errors
Cucumber HTML
cucumber-report/index.html
Open the file in a browser
Business 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.)
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.
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.
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.
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.
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.
❓ 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.