Playwright + TS · Lesson 27 of 36

0/36 done

Module 27: Test Data & Parameterization

27. Data-Driven Testing & Dynamic Parameterization

18 minlesson

Try it yourself

Implement generateCartesianMatrix:

  1. Accept listA of type T[] and listB of type U[].
  2. Return an array of all combined pairs [T, U][].

The editor has a worked example. Read it, tweak it, then press Mark as complete.

1. Parameterized Tests with Arrays

Loop over test data items to generate distinct tests at compile-time:

typescript
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

typescript
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:

typescript
export function generateTestCustomer() {
  const uniqueId = Date.now();
  return {
    name: `Customer ${uniqueId}`,
    email: `customer_${uniqueId}@testcompany.com`,
    creditCardEnding: "4242",
  };
}

Key Takeaways & Walkthrough Summary

Data-driven testing allows you to run the same test scenario across multiple inputs without duplicating code. In this lesson, we will explore static JSON test fixtures, parameterized test loops, and dynamic test data generation to test edge cases thoroughly. Let's parameterize our tests!

Part of the Playwright + TS course (Playwright with TypeScript). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

How does Playwright report parameterized tests in the HTML reporter?

Each iteration of the loop creates a completely distinct test entry in the report with its own execution time, video, and trace file.

Can I load CSV files directly into Playwright tests?

Yes! You can use the 'csv-parse/sync' npm package to synchronously parse CSV files at the top level of your spec file.

Finished reading?

Review the worked example in the editor, then mark the lesson complete.

TypeScript
Skip