27. Data-Driven Testing & Dynamic Parameterization

1. Parameterized Tests with Arrays

Loop over test data items to generate distinct tests at compile-time:
import { test, expect } from "@playwright/test";

const searchScenarios = [
{ query: "Playwright", expectedCount: 15 },
{ query: "TypeScript", expectedCount: 25 },
{ query: "Selenium", expectedCount: 8 },
];

for (const { query, expectedCount } of searchScenarios) {
test(search for "${query}" returns at least ${expectedCount} results, async ({ page }) => {
await page.goto("/search");
await page.getByPlaceholder("Search").fill(query);
await page.keyboard.press("Enter");

const results = page.locator(".result-card");
await expect(results).toHaveCount(expectedCount);
});
}

---

2. Loading Static JSON Test Fixtures

import usersData from "../data/users.json";

for (const user of usersData) {
test(validate permissions for role ${user.role}, async ({ page }) => {
// executes per user row
});
}

---

3. Generating Unique Random Data

Avoid collision in parallel runs by generating dynamic emails and names:
export function generateTestCustomer() {
  const uniqueId = Date.now();
  return {
    name: Customer ${uniqueId},
    email: customer_${uniqueId}@testcompany.com,
    creditCardEnding: "4242",
  };
}

Task

  • Implement generateCartesianMatrix:
  • 1. Accept listA of type T[] and listB of type U[].
  • 2. Return an array of all combined pairs [T, U][].
πŸ’‘Common doubts
Did you like the problem?
Lesson 27 of 36
TypeScript
Loading code editor…
Next