Playwright TypeScript Test Data Generator: Step-by-Step Guide (2026) | TechSarvam

1. Introduction to Test Data Generation in Playwright TypeScript

Test data is an important part of software testing. Every automated test requires data to validate application functionality, including usernames, passwords, email addresses, customer details, and product information.

When writing Playwright automation scripts, using the same hardcoded data repeatedly can create problems. Tests may fail because an email address already exists, a record was modified by another test, or multiple workers are trying to use the same account.

A Playwright TypeScript test data generator helps solve these problems by creating dynamic and reusable test data.

Using TypeScript and libraries such as Faker.js, QA Automation Engineers can generate realistic names, email addresses, phone numbers, addresses, and other test values.

For example, consider a registration application. Instead of using the same email address for every test, Faker.js can generate a different email address for each execution.

This approach improves test isolation, reduces duplicate data problems, and makes regression testing more reliable.

In this tutorial, we will build a complete test data generation utility using Playwright, TypeScript, and Faker.js.

2. Why Automated Testing Needs Dynamic Test Data

Automated testing requires different types of data to validate application behavior.

For example, an e-commerce application may require:

  • Customer names.
  • Email addresses.
  • Passwords.
  • Product names.
  • Shipping addresses.
  • Payment test details.
  • Order information.

There are two common approaches to managing test data.

Static Test Data vs Dynamic Test Data

Static test dataDynamic test data
Uses predefined valuesGenerates values during execution
Can create duplicate recordsCan create unique records
Easy for fixed scenariosUseful for repeated execution
Requires manual updatesCan generate new values automatically
Suitable for controlled test casesSuitable for registration and data creation

Example of Static Test Data

const user = {

  name: ‘John Smith’,

  email: ‘john@example.com’,

  password: ‘Test@123’

};

If the application does not allow duplicate email addresses, repeated registration tests may fail.

Example of Dynamic Test Data

const user = {

  name: `User${Date.now()}`,

  email: `user${Date.now()}@example.com`,

  password: ‘Test@123’

};

This generates different values using the current timestamp.

However, timestamps are not guaranteed to be unique in every concurrent execution scenario. For more realistic and reliable data generation, Faker.js combined with a unique identifier is a better approach.

3. Prerequisites and Project Setup

Before starting the Playwright TypeScript test data generator tutorial, install the following tools:

ToolPurpose
Node.jsExecutes JavaScript and TypeScript
npmDependency management
PlaywrightBrowser automation
TypeScriptType-safe programming
Faker.jsDynamic test data generation
VS CodeCode development

Step 1: Create a Project

mkdir playwright-test-data

cd playwright-test-data

Initialize Playwright:

npm init playwright@latest

Select TypeScript when prompted.

Step 2: Install Faker.js

Install the Faker library:

npm install @faker-js/faker

Faker provides methods for generating realistic test data.

Step 3: Verify Installation

npx playwright –version

Check the installed Faker package:

npm list @faker-js/faker

4. Generate Random Data Using JavaScript and TypeScript

Before integrating Faker.js, understand how to generate basic dynamic data using JavaScript and TypeScript.

Generate Unique Email Addresses

const email = `user${Date.now()}@example.com`;

console.log(email);

Generate Random Numbers

const randomNumber = Math.floor(

  Math.random() * 10000

);

console.log(randomNumber);

Generate Dynamic User Information

interface User {

  name: string;

  email: string;

  age: number;

}

const user: User = {

  name: ‘TestUser’,

  email: `test${Date.now()}@example.com`,

  age: 25

};

console.log(user);

These techniques are useful for simple scenarios.

However, manually generating realistic names, addresses, and other information requires additional code.

Faker.js provides ready-made methods for these requirements.

5. Integrate Faker.js with Playwright

Faker.js is a popular JavaScript and TypeScript library for generating realistic fake data.

It supports multiple data categories, including:

  • Person information.
  • Internet usernames and emails.
  • Addresses.
  • Phone numbers.
  • Company information.
  • Product details.
  • Dates and numbers.

Step 1: Import Faker

Create a file named test-data/userData.ts.

import { faker } from ‘@faker-js/faker’;

const name = faker.person.fullName();

const email = faker.internet.email();

const password = faker.internet.password();

console.log(name);

console.log(email);

console.log(password);

Run the script through a TypeScript runner such as npx tsx, after installing it as a development dependency:

npm install -D tsx

npx tsx test-data/userData.ts

Step 2: Generate Registration Data

import { faker } from ‘@faker-js/faker’;

export const generateUser = () => {

  return {

    firstName: faker.person.firstName(),

    lastName: faker.person.lastName(),

    email: faker.internet.email(),

    password: ‘Test@123’,

    phone: faker.string.numeric(10)

  };

};

console.log(generateUser());

Example output:

{

  “firstName”: “Alex”,

  “lastName”: “Taylor”,

  “email”: “alex.taylor@example.com”,

  “password”: “Test@123”,

  “phone”: “9876543210”

}

The generated values change between executions.

For a real application, validate the generated phone number against the application’s country-specific rules. Faker-generated values are synthetic and should not be treated as real contact information.

Step 3: Use a Seed for Reproducible Data

Sometimes, you need to generate the same test data again when investigating a failure.

Faker supports seeded data generation:

import { faker } from ‘@faker-js/faker’;

faker.seed(12345);

console.log(faker.person.fullName());

console.log(faker.internet.email());

Using the same seed with the same Faker version and generation sequence helps reproduce generated values.

This is useful when debugging regression tests.

6. Create Reusable Test Data Utilities and Factories

In professional Playwright frameworks, test data generation should be reusable.

Instead of generating user details directly inside every test file, create a centralized utility.

Step 1: Create a Data Factory

Create test-data/userFactory.ts.

import { faker } from ‘@faker-js/faker’;

export interface UserData {

  firstName: string;

  lastName: string;

  email: string;

  password: string;

}

export function createUser(): UserData {

  return {

    firstName: faker.person.firstName(),

    lastName: faker.person.lastName(),

    email: `qa-${faker.string.uuid()}@example.com`,

    password: ‘Test@123’

  };

}

The UUID helps reduce the possibility of duplicate email addresses.

Step 2: Create Multiple Users

import { createUser } from ‘./userFactory’;

const users = Array.from(

  { length: 5 },

  () => createUser()

);

console.log(users);

This creates five independent user objects.

Step 3: Create Product Test Data

Create test-data/productFactory.ts.

import { faker } from ‘@faker-js/faker’;

export function createProduct() {

  return {

    name: faker.commerce.productName(),

    price: faker.commerce.price({

      min: 100,

      max: 5000

    }),

    category: faker.commerce.department()

  };

}

Now you can generate user and product data from different factories.

This structure improves maintainability because changes to data generation logic can be made in one place.

7. Manage JSON, CSV, and Environment-Based Test Data

Not every test requires randomly generated information.

Some scenarios require fixed data, such as invalid login credentials, account roles, or predefined product categories.

A professional framework should support static and dynamic test data.

A. Manage JSON Test Data

Create test-data/users.json:

{

  “validUser”: {

    “email”: “test@example.com”,

    “password”: “Test@123”

  },

  “invalidUser”: {

    “email”: “invalid@example.com”,

    “password”: “WrongPassword”

  }

}

Import the JSON data into TypeScript:

import users from ‘../test-data/users.json’;

console.log(users.validUser.email);

Ensure your tsconfig.json includes:

{

  “compilerOptions”: {

    “resolveJsonModule”: true,

    “esModuleInterop”: true

  }

}

B. Manage CSV Test Data

CSV files are useful when you need multiple predefined test scenarios.

Example test-data/login.csv:

email,password,expected

valid@example.com,Test@123,success

invalid@example.com,Wrong123,failure

For larger CSV datasets, install a CSV parsing library such as csv-parse.

npm install csv-parse

import { parse } from ‘csv-parse/sync’;

import { readFileSync } from ‘node:fs’;

const content = readFileSync(

  ‘test-data/login.csv’,

  ‘utf8’

);

const records = parse(content, {

  columns: true,

  skip_empty_lines: true

});

console.log(records);

C. Manage Environment-Based Test Data

Use environment variables to switch between environments.

For example:

const baseURL =

  process.env.BASE_URL || ‘https://example.com’;

Execute tests with a different environment:

BASE_URL=https://qa.example.com npx playwright test

On Windows PowerShell:

$env:BASE_URL=”https://qa.example.com”

npx playwright test

Never store production passwords or sensitive customer information in JSON or CSV files committed to Git.

8. Use Generated Data in Forms, API Tests, and Page Object Model

Let’s understand how to use a Playwright TypeScript test data generator in real automation scenarios.

A. Registration Form Testing

Create tests/register.spec.ts:

import { test, expect } from ‘@playwright/test’;

import { createUser } from ‘../test-data/userFactory’;

test(‘Register a new user’, async ({ page }) => {

  const user = createUser();

  await page.goto(‘/register’);

  await page.getByLabel(‘First Name’).fill(

    user.firstName

  );

  await page.getByLabel(‘Last Name’).fill(

    user.lastName

  );

  await page.getByLabel(‘Email’).fill(

    user.email

  );

  await page.getByLabel(‘Password’).fill(

    user.password

  );

  await page.getByRole(‘button’, {

    name: ‘Register’

  }).click();

  await expect(

    page.getByText(‘Registration successful’)

  ).toBeVisible();

});

Every execution generates a new user.

B. API Testing with Generated Data

Playwright supports API testing through its request fixture.

import { test, expect } from ‘@playwright/test’;

import { createUser } from ‘../test-data/userFactory’;

test(‘Create user using API’, async ({ request }) => {

  const user = createUser();

  const response = await request.post(

    ‘/api/users’,

    {

      data: user

    }

  );

  expect(response.status()).toBe(201);

  const responseBody = await response.json();

  expect(responseBody.email).toBe(user.email);

});

This example assumes the application exposes a compatible API endpoint and returns the submitted email address.

API-generated data can also be used to prepare backend records before UI testing.

C. Use Generated Data with Page Object Model

Create pages/RegisterPage.ts:

import { Page } from ‘@playwright/test’;

import { UserData } from ‘../test-data/userFactory’;

export class RegisterPage {

  constructor(private page: Page) {}

  async register(user: UserData) {

    await this.page.getByLabel(‘First Name’)

      .fill(user.firstName);

    await this.page.getByLabel(‘Last Name’)

      .fill(user.lastName);

    await this.page.getByLabel(‘Email’)

      .fill(user.email);

    await this.page.getByLabel(‘Password’)

      .fill(user.password);

    await this.page.getByRole(‘button’, {

      name: ‘Register’

    }).click();

  }

}

The test now becomes simpler:

import { test, expect } from ‘@playwright/test’;

import { RegisterPage } from ‘../pages/RegisterPage’;

import { createUser } from ‘../test-data/userFactory’;

test(‘Register user using POM’, async ({ page }) => {

  const registerPage = new RegisterPage(page);

  const user = createUser();

  await page.goto(‘/register’);

  await registerPage.register(user);

  await expect(

    page.getByText(‘Registration successful’)

  ).toBeVisible();

});

This separates test data generation, page actions, and test validation.

9. Handle Unique Data, Cleanup, and Parallel Execution

Parallel execution can create data conflicts when multiple tests use the same account or record.

For example, two registration tests using the same email address may cause one test to fail.

Follow these practices:

  1. Generate unique identifiers for every test.
  2. Avoid sharing mutable accounts across workers.
  3. Create independent test records.
  4. Delete generated records when appropriate.
  5. Use API setup and teardown for faster data management.

Use API-Based Test Data Cleanup

import { test, expect } from ‘@playwright/test’;

import { createUser } from ‘../test-data/userFactory’;

test(‘Create and delete user’, async ({ request }) => {

  const user = createUser();

  const response = await request.post(‘/api/users’, {

    data: user

  });

  expect(response.status()).toBe(201);

  const createdUser = await response.json();

  const deleteResponse = await request.delete(

    `/api/users/${createdUser.id}`

  );

  expect(deleteResponse.ok()).toBeTruthy();

});

This example assumes the application supports user creation and deletion APIs.

For larger test suites, use fixtures to centralize setup and cleanup.

10. Integrate Test Data Generation with CI/CD

A Playwright TypeScript test data generator can also work inside GitHub Actions and Jenkins.

For GitHub Actions, generated test data can be created automatically whenever a workflow runs.

Example:

name: Playwright Data Tests

on:

  push:

    branches: [main]

jobs:

  test:

    runs-on: ubuntu-latest

    steps:

      – uses: actions/checkout@v6

      – uses: actions/setup-node@v6

        with:

          node-version: lts/*

          cache: npm

      – run: npm ci

      – run: npx playwright install –with-deps chromium

      – name: Run tests

        run: npx playwright test

        env:

          BASE_URL: ${{ secrets.BASE_URL }}

The test data factory generates fresh records during execution.

For Jenkins, the same test suite can execute through:

pipeline {

    agent any

    stages {

        stage(‘Install’) {

            steps {

                sh ‘npm ci’

            }

        }

        stage(‘Install Browsers’) {

            steps {

                sh ‘npx playwright install –with-deps chromium

            }

        }

        stage(‘Run Tests’) {

            steps {

                sh ‘npx playwright test’

            }

        }

    }

}

This approach makes test data generation part of the automated regression testing process.

11. Best Practices and Common Troubleshooting

Best Practices

PracticeBenefit
Use Faker.jsGenerates realistic data
Create reusable factoriesReduces duplicate code
Generate unique identifiersAvoids duplicate records
Use JSON for fixed dataSupports predictable scenarios
Use environment variablesSupports multiple environments
Clean up generated recordsPrevents database pollution
Use fixturesCentralizes test setup and cleanup
Use seeded Faker dataHelps reproduce failures
Avoid real customer dataProtects privacy
Isolate parallel testsPrevents data conflicts

Common Problems and Solutions

Problem 1: Duplicate Email Addresses

Solution: Generate UUID-based email addresses.

Problem 2: Tests Fail During Parallel Execution

Solution: Give each test independent records and avoid shared mutable data.

Problem 3: Generated Data Is Not Reproducible

Solution: Use Faker seeds and preserve the seed and generation sequence when investigating failures.

Problem 4: API Cleanup Fails

Solution: Verify API permissions, endpoint behavior, and whether the test record was created successfully.

Problem 5: Environment Variables Are Undefined

Solution: Verify the CI/CD configuration and use a fallback value where appropriate.

12. Frequently Asked Questions

Q1. Is Playwright TypeScript test data generator suitable for beginners?

Yes. Beginners can start with JavaScript random values and gradually learn Faker.js, reusable factories, JSON data, and API-based test data management.

Q2. How do I get started with Playwright TypeScript test data generator?

Create a Playwright TypeScript project and install Faker.js:

npm install @faker-js/faker

Create a reusable factory function, import it into your test files, and generate unique data for each test execution.

Q3. What is Playwright TypeScript test data generator?

It is a reusable utility or framework component that generates dynamic test values for Playwright automation scripts using TypeScript and libraries such as Faker.js.

Q4. Why is Faker.js used in Playwright?

Faker.js generates realistic names, email addresses, phone numbers, addresses, and other test information without manually creating every value.

Q5. Can I use Faker.js for API testing?

Yes. Generate request payloads using Faker.js and pass them to Playwright’s API testing methods.

Q6. How do I avoid duplicate test data?

Use UUIDs or other reliable unique identifiers, isolate test records, and clean up generated data after execution.

Q7. Can I use static and dynamic test data together?

Yes. Static data is useful for predefined scenarios, while dynamic data is useful for registration, account creation, and repeated execution.

Leave a Comment

Your email address will not be published. Required fields are marked *