How to Generate Unique Test Data for Every Playwright Test

 


Have you ever run a Playwright test successfully once, only to see it fail the next time?

One common reason is duplicate test data.

For example, a registration test creates an account using testuser@example.com. When you run the test again, the website reports that the email address is already registered.

The problem may not be your Playwright script. The test is trying to create data that already exists.

The solution is to generate unique test data whenever a test needs a new record.

In this guide, you will learn how to generate unique email addresses, create reusable test data, use Playwright fixtures, clean up test records, and avoid common mistakes.

The examples use JavaScript and Playwright Test.

1. What Is Unique Test Data?

Unique test data is information that does not conflict with the data used by other tests or previous test executions.

For example:

Test 1:

user-a123@example.com

Test 2:

user-b456@example.com

Test 3:

user-c789@example.com

Each address is different.

Unique data is useful when testing:

  • User registration.

  • Customer creation.

  • Order creation.

  • Shopping cart workflows.

  • Account settings.

  • Database records.

  • API operations.

However, not every test requires unique data.

A test that checks whether the login page displays a heading can use fixed data or no account data at all.

Generate unique values when the application requires new or isolated records.

2. Create a Basic Playwright Project

If you already have a Playwright project, you can skip this step.

Otherwise, install Playwright Test using the official setup instructions:

Playwright installation guide

After creating the project, you can write a test like this:

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


test('should open the login page', async ({ page }) => {

  await page.goto('https://example.com');


  await expect(page).toHaveTitle(/Example Domain/);

});


This simple test checks whether the example website opens and displays the expected title.

It does not create an account, so it does not need unique registration data.

Now let's look at tests that do.

3. Method One: Generate Unique Data Using Date.now()

JavaScript provides a method called Date.now().

It returns the current time in milliseconds.

You can use that value to generate different test data.

function createUniqueEmail() {

  return `user-${Date.now()}@example.com`;

}


console.log(createUniqueEmail());


Example output:

user-1790000000000@example.com

When the function runs again at a different time, it will usually generate a different email address.

When should you use this method?

Use it for simple test scenarios where a timestamp is sufficient.

However, timestamps are not guaranteed to be unique in every possible situation. Two workers may generate data at nearly the same time.

For stronger uniqueness, use the next method.

4. Method Two: Generate Unique Data Using UUID

A UUID is a long identifier designed to be practically unique.

Node.js provides a built-in function for generating UUIDs.

import { randomUUID } from 'node:crypto';


function createUniqueEmail() {

  return `user-${randomUUID()}@example.com`;

}


console.log(createUniqueEmail());


Example output:

user-550e8400-e29b-41d4-a716-446655440000@example.com

Each function call produces a new UUID.

This is a good general-purpose choice for creating unique identifiers in Playwright tests.

Why is UUID useful?

It helps reduce the risk of:

  • Duplicate registration emails.

  • Duplicate test record identifiers.

  • Conflicts between parallel tests.

  • Repeated test data across multiple runs.

Remember that uniqueness alone does not make a value valid.

Your application may require a particular email domain, a minimum password length, or an existing customer record.

Always follow the application's rules.

5. Create a Reusable Test Data Function

Instead of generating an email address separately in every test, create a reusable function.

Create a file called test-data.js.

import { randomUUID } from 'node:crypto';


export function createTestUser() {

  return {

    name: 'Playwright Test User',

    email: `user-${randomUUID()}@example.com`,

    password: 'TestPassword123!'

  };

}


This function returns a new user object whenever you call it.

Example:

import { createTestUser } from './test-data.js';


const user1 = createTestUser();

const user2 = createTestUser();


console.log(user1.email);

console.log(user2.email);


The two calls generate different email addresses in ordinary use.

Why is this approach useful?

Imagine your project contains 50 registration-related tests.

Without a shared function, you might repeat the same data-generation logic throughout the project.

With a reusable function, you can maintain that logic in one place.

If you later need to change how test email addresses are generated, you can update the function instead of editing every test.

6. Use Unique Data in a Registration Test

Now let's use the generated data in a Playwright test.

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

import { createTestUser } from './test-data.js';


test('should register a new user', async ({ page }) => {

  const user = createTestUser();


  await page.goto('https://your-test-application.example/register');


  await page.getByLabel('Name').fill(user.name);

  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();

});


Important: The URL, form labels, button name, and success message are examples. Replace them with the real values from your application.

This test follows a simple process:

  1. Generate a new user.

  2. Open the registration page.

  3. Enter the generated information.

  4. Submit the form.

  5. Verify the expected result.

Because the test generates a new email address, it is less likely to fail because of an account created during an earlier run.

The example assumes the application permits registration with the generated email address. If it requires email verification, additional setup may be necessary.

7. Use Playwright Fixtures to Share Test Data

A fixture lets you prepare reusable data for your tests.

Instead of importing a function into every test, you can create a custom fixture.

Create a file named fixtures.js.

import { test as base, expect } from '@playwright/test';

import { createTestUser } from './test-data.js';


export const test = base.extend({

  testUser: async ({}, use) => {

    const user = createTestUser();


    await use(user);

  }

});


export { expect };


Now you can use the fixture in a test.

import { test, expect } from './fixtures.js';


test('should generate a unique test user', async ({ testUser }) => {

  expect(testUser.name).toBe('Playwright Test User');

  expect(testUser.email).toContain('@example.com');

});


What happens here?

The fixture creates the user data before the test runs.

The test receives that data through testUser.

After the test completes, the fixture finishes.

This fixture only generates data. It does not create a real account or delete an account from your application.

If your tests create real records, you may need additional setup and teardown logic.

Use fixtures when multiple tests need the same kind of prepared resource.

8. Generate Different Test Data for Different Scenarios

Not all tests should use the same type of data.

Consider these scenarios:

Test scenario

Suitable test data

Valid registration

Unique, valid email address

Invalid email validation

Fixed invalid email examples

Password validation

Passwords covering required and invalid cases

Duplicate account validation

An existing controlled test account

User permissions

Accounts with different roles

Search functionality

Known search terms and expected results

Order creation

Valid customer and product records

For example, an invalid email test may use the same invalid value every time:

const invalidEmails = [

  'wrong-email',

  '@example.com',

  'missing-domain@'

];


There is no need to generate random values for every validation case.

The goal is to use data that makes the test meaningful and repeatable.

9. Use API Requests to Create Test Records

Sometimes, creating data through the browser is unnecessary.

Suppose you want to test the order history page.

The purpose of the test is to check whether existing orders are displayed correctly.

You may not need to create every customer and order through the user interface.

If your test environment offers a suitable API, you can create the required record through that API.

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

import { randomUUID } from 'node:crypto';


test('should create a customer using an API', async ({ request }) => {

  const email = `customer-${randomUUID()}@example.com`;


  const response = await request.post(

    'https://api.example.com/test/customers',

    {

      data: {

        name: 'Test Customer',

        email

      }

    }

  );


  expect(response.ok()).toBeTruthy();

});


This is an illustrative example. It requires a compatible API endpoint, the correct request format, and any necessary authentication.

API setup is useful when it prepares data faster and more consistently than repeating UI actions.

However, if you are testing the registration process itself, you should still test registration through the UI.

10. Clean Up Test Data After Execution

Unique test data reduces conflicts, but it can also create many records.

Suppose your suite creates 100 new users every day.

After several weeks, the test environment may contain thousands of accounts that are no longer needed.

Depending on your application, you may need to:

  • Delete temporary users.

  • Remove test orders.

  • Reset modified settings.

  • Clear temporary files.

  • Restore controlled test data.

A cleanup strategy should be safe and predictable.

For API-created records, you can delete the specific record after the test, provided the application supports it.

Always restrict cleanup operations to test data. Never use a broad deletion operation that might remove real customer records.

For tests that must inspect the created data after execution, cleanup can be delayed or performed by a separate scheduled process.

11. Avoid These Common Mistakes

Mistake 1: Using the same email for every registration test

Why it fails: The application may reject duplicate registrations.

What to do: Generate a new email address for each independent registration test.

Mistake 2: Generating random data that violates validation rules

Why it fails: The application rejects the value.

What to do: Generate values that follow the actual application requirements.

Mistake 3: Assuming UUID solves every test conflict

Why it fails: Tests can still interfere with shared accounts, products, permissions, or database records.

What to do: Isolate every resource that a test modifies.

Mistake 4: Creating data but never cleaning it up

Why it fails: Old records accumulate and may affect future tests.

What to do: Add appropriate cleanup or a controlled test-environment reset.

Mistake 5: Sharing mutable test data between parallel tests

Why it fails: One test can change data while another test expects its original value.

What to do: Give tests independent records or carefully manage shared resources.

Mistake 6: Saving real passwords in source code

Why it fails: Credentials may be exposed in repositories or reports.

What to do: Use dedicated test credentials and secure environment configuration.

12. Best Practices for Unique Test Data

Follow these practices to improve the reliability of your Playwright tests.

Generate data only when necessary. A static test does not need random information if its purpose is to verify a fixed result.

Use UUIDs for unique identifiers. They are a practical choice for many registration and record-creation tests.

Create reusable functions. Keep common data-generation logic in one place.

Use fixtures for shared setup. Fixtures help prepare data consistently across tests.

Keep tests independent. A test should not depend unnecessarily on another test having run successfully.

Use APIs when appropriate. API-based setup can save time when the UI is not the feature under test.

Clean up temporary records. Keep the test environment manageable.

Protect sensitive information. Never expose production credentials or private customer data.

Check parallel execution. Run tests under the same parallel configuration used by your CI pipeline.

Keep test data understandable. Descriptive names make failures easier to investigate.

Frequently Asked Questions

How can I create a unique email address in Playwright?

Import randomUUID from node:crypto and use it to generate a unique identifier. Append the identifier to an email address on a domain suitable for your test environment.

Is Date.now() enough for unique Playwright test data?

It is often sufficient for simple tests, but it does not guarantee uniqueness across simultaneous executions. A UUID is a stronger general-purpose choice.

Should every Playwright test use random data?

No. Use random or unique data when the test needs new records or independent resources. Fixed data is often better for validation tests and scenarios that need predictable inputs.

Can fixtures generate unique data for each test?

Yes. A fixture can call a data-generation function and provide the resulting data to each test.

How can I stop duplicate user errors in Playwright?

Generate unique email addresses for registration tests, or reset existing test accounts through a controlled setup process.

Does unique test data prevent all flaky tests?

No. It reduces failures caused by duplicate or conflicting data. Timing issues, application defects, unstable environments, poor synchronization, and shared resources can still cause flaky tests.

Conclusion

Generating unique test data is a simple but important practice for reliable Playwright automation.

Start by creating a reusable data-generation function. Use UUIDs when independent records are required. Introduce fixtures when several tests need the same setup, and use API-based preparation when it is appropriate for the scenario.

Finally, isolate resources and clean up temporary data safely.

These practices help your automation tests run more consistently and make failures easier to investigate.

Learn More

Visit PlaywrightMasters.in to explore Playwright automation training and related learning resources.

You can continue with topics such as:

Learn the concepts, practice them in a controlled test project, and build automation that is easier to trust and maintain.


Comments

Popular posts from this blog

How to Run Only Smoke Tests in Playwright: Step-by-Step Guide

How to Test REST APIs Using Playwright

Playwright Multiple Tabs and Windows Explained: A Practical Guide