How to Read CSV Test Data in Playwright

 


Suppose you need to test a registration page with 100 different input combinations.

You have a spreadsheet containing usernames, email addresses, passwords, and expected results.

Instead of manually copying every row into your Playwright test file, you can store the data in a CSV file and use it to create automated test scenarios.

Reading CSV test data in Playwright allows you to separate tabular test inputs from your automation code.

This is especially useful when testers need to maintain large datasets or when test cases are prepared using spreadsheet software.

In this tutorial, you will learn how to create a CSV file, read it with TypeScript, convert its rows into test data, and use that data in Playwright tests.

You will also learn how to handle headers, missing values, commas inside fields, duplicate records, and common CSV parsing problems.

What Is a CSV File?

CSV stands for Comma-Separated Values.

It is a text format that stores information in rows and columns.

Consider this example:

username,password,expectedResult

validUser,CorrectPassword123,success

invalidUser,WrongPassword123,failure

emptyUser,,validationError


The first row contains the column names.

The remaining rows contain the test data.

Each row represents a different test scenario.

The columns describe the values that your automation test can use.

For example:

  • username contains the username.

  • password contains the password.

  • expectedResult describes the expected outcome.

CSV is useful when the test data is naturally represented as a table.

You can create or edit it in a spreadsheet application or a text editor without changing your Playwright test logic.

Why Use CSV Files for Playwright Testing?

Imagine that your testing team maintains 200 search scenarios in a spreadsheet.

If the expected search terms change, updating a separate automation test for every row would be inconvenient.

With CSV-based testing, the team can maintain the dataset separately from the test code.

This approach is useful when:

  • Testers maintain data in spreadsheet software.

  • You need to validate many input combinations.

  • Business scenarios are reviewed in tabular form.

  • The same data is reused in different test suites.

  • Test data changes more frequently than the test workflow.

  • You want test scenarios to be easy to review.

However, CSV is not ideal for every situation.

If your test data contains complex nested objects, arrays, or multiple related entities, JSON may be easier to manage.

The right format depends on the shape of your data and how your team works.

What You Need Before Reading CSV Data

You should have:

  1. A working Node.js environment.

  2. A Playwright Test project.

  3. Basic knowledge of JavaScript or TypeScript.

  4. A CSV file containing test data.

  5. A test application that you are authorized to automate.

If you have not created a Playwright project yet, first follow the setup instructions in the PlaywrightMasters Playwright Framework Guide.

For this tutorial, the examples use TypeScript and Playwright Test.

Step 1: Create a CSV Test-Data File

Inside your project, create a folder named test-data.

Create a file named search-data.csv.

Use the following example:

testName,searchTerm,expectedText

Search existing product,laptop,Laptop

Search another product,keyboard,Keyboard

Search missing product,product-does-not-exist,No products found


Each row represents a search scenario.

For the first row, the test searches for laptop and expects the page to display a matching product.

For the second row, the test searches for keyboard.

For the third row, the test searches for a term that should not match any product and expects an appropriate empty-state message.

These values are illustrative. Replace the expected text with the actual behavior of your application.

Your project can now look like this:

playwright-project/

│

├── tests/

│   └── search-data.spec.ts

│

├── test-data/

│   └── search-data.csv

│

├── playwright.config.ts

└── package.json


Step 2: Install a CSV Parsing Library

CSV looks simple, but correctly parsing it can become complicated.

For example, consider this row:

testName,expectedText

"Search product, premium edition","Product, premium edition"


Some fields contain commas inside quotation marks.

A basic split(',') operation cannot correctly handle every valid CSV file because it may treat commas inside quoted fields as column separators.

CSV can also contain escaped quotation marks, empty fields, and line breaks inside quoted values.

For this reason, a dedicated parser is preferable for real projects.

One commonly used option is csv-parse, from the csv package ecosystem.

Install it with:

npm install csv-parse


This library provides a parser that can handle common CSV formatting rules.

You can review its documentation at the official CSV Parse documentation.

Step 3: Create a Reusable CSV Reader

Instead of placing CSV parsing logic inside every test file, create a reusable helper.

Create a file named utils/read-csv.ts.

import fs from 'node:fs';

import path from 'node:path';

import { parse } from 'csv-parse/sync';


export type SearchTestData = {

  testName: string;

  searchTerm: string;

  expectedText: string;

};


export function readSearchData(): SearchTestData[] {

  const filePath = path.resolve(

    process.cwd(),

    'test-data',

    'search-data.csv'

  );


  const fileContent = fs.readFileSync(filePath, 'utf8');


  const records = parse(fileContent, {

    columns: true,

    skip_empty_lines: true,

    bom: true,

    trim: true

  }) as Record<string, string>[];


  return records.map((record, index) => {

    const requiredColumns = [

      'testName',

      'searchTerm',

      'expectedText'

    ];


    for (const column of requiredColumns) {

      if (!(column in record)) {

        throw new Error(

          `Missing CSV column "${column}" in record ${index + 1}`

        );

      }

    }


    const testName = record.testName;

    const searchTerm = record.searchTerm;

    const expectedText = record.expectedText;


    if (!testName || !searchTerm || !expectedText) {

      throw new Error(

        `Missing required value in CSV record ${index + 1}`

      );

    }


    return {

      testName,

      searchTerm,

      expectedText

    };

  });

}


This helper reads the CSV file and converts its rows into an array of TypeScript objects.

Let's understand the important parts.

fs.readFileSync()

const fileContent = fs.readFileSync(filePath, 'utf8');


This reads the file contents as text.

The utf8 encoding allows the file to be interpreted as text rather than as raw binary data.

path.resolve()

const filePath = path.resolve(

  process.cwd(),

  'test-data',

  'search-data.csv'

);


This builds the file path from the current working directory.

Using a resolved path makes the intended file location clear.

columns: true

columns: true


This tells the parser to use the first CSV row as the column names.

Instead of receiving anonymous arrays, you receive objects with properties such as testName and searchTerm.

skip_empty_lines: true

This tells the parser to skip completely empty lines.

It does not mean that every row containing empty fields will be ignored.

For example, a row with an empty password still contains data and should be handled according to the test scenario.

trim: true

This removes surrounding whitespace from parsed field values.

That can prevent accidental spaces from affecting comparisons.

bom: true

This helps handle a UTF-8 byte-order mark, which may appear in some CSV files exported by spreadsheet applications.

Required-column validation

The helper checks that important columns exist and that required values are present.

This helps identify malformed data before the test tries to interact with the application.

For a larger project, you may want to validate duplicate column names, unexpected columns, allowed values, and row-specific requirements as well.

Step 4: Use CSV Data in a Playwright Test

Now create tests/search-data.spec.ts.

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

import { readSearchData } from '../utils/read-csv';


const searchData = readSearchData();


test.describe('CSV-driven search tests', () => {

  for (const data of searchData) {

    test(data.testName, async ({ page }) => {

      await page.goto('/products');


      await page

        .getByRole('textbox', { name: 'Search products' })

        .fill(data.searchTerm);


      await page

        .getByRole('button', { name: 'Search' })

        .click();


      await expect(

        page.getByText(data.expectedText, { exact: false })

      ).toBeVisible();

    });

  }

});


This example assumes the application contains a /products page, a search textbox labelled Search products, and a Search button.

You must adapt the page URL, locators, and expected text to your application.

The example also assumes that every row contains a non-empty expectedText value. If your application represents an empty result differently, adjust the CSV structure and assertion accordingly.

What happens when the test runs?

First, the test imports the CSV reader.

The reader loads the file and converts its rows into objects.

Next, the loop creates a separate test declaration for each row.

During each test, Playwright opens the product page, enters the search term, and submits the search.

Finally, the assertion checks whether the expected text appears.

This lets you manage multiple search scenarios through one dataset without copying the entire test implementation.

Step 5: Configure the Base URL

In your Playwright configuration, define the URL of your test application.

For example:

import { defineConfig } from '@playwright/test';


export default defineConfig({

  use: {

    baseURL: 'http://127.0.0.1:3000'

  }

});


The example assumes your application is running locally on port 3000.

If your application uses another port, update the configuration.

The relative URL in your test:

await page.goto('/products');


will then resolve against the configured base URL.

For a production-like testing setup, use an appropriate test or staging environment rather than accidentally running destructive tests against a live production application.

Step 6: Run the CSV-Driven Tests

Execute:

npx playwright test tests/search-data.spec.ts


Playwright runs the test cases declared from the CSV data.

To watch the browser while debugging, use:

npx playwright test tests/search-data.spec.ts --headed


If a test fails, inspect the error message and confirm whether the issue comes from:

  • The CSV data.

  • The page locator.

  • The application response.

  • The expected result.

  • The environment configuration.

A CSV-driven test can fail because of incorrect input data just as easily as it can fail because of an application defect.

Do not automatically assume every failure is caused by Playwright.

How to Read CSV Data with Empty Values

Consider this CSV file:

testName,username,password,expectedResult

Valid login,userA,Password123,success

Empty password,userA,,validationError

Empty username,,Password123,validationError


The empty values are intentional.

They allow you to test how the application handles missing input.

Do not automatically reject every empty field during CSV parsing.

Instead, decide which fields must always be present and which fields are allowed to be empty for a particular scenario.

For example, the testName should normally be required, but an empty password may be necessary to test validation behavior.

A good CSV reader validates the structure of the data without preventing legitimate negative test cases.

How to Handle Commas and Special Characters in CSV Files

CSV data can contain commas, quotation marks, and other characters that affect parsing.

For example:

testName,searchTerm,expectedText

"Search premium products","laptop, premium","Premium laptop"


The comma inside the quoted search term belongs to the field. It should not create another column.

A proper CSV parser understands this structure.

You should also consider how the file is encoded.

If a file contains non-English text, make sure the source and reader use compatible encodings.

For most modern projects, UTF-8 is a sensible default.

If a CSV file comes from an external system, inspect a few parsed records before relying on the dataset in a large test suite.

How to Validate CSV Data Before Running Tests

A test-data file can be syntactically valid but logically incorrect.

For example:

testName,searchTerm,expectedText

Search laptop,,Laptop


The file contains the expected columns, but the search term is empty.

That may be intentional, or it may be a mistake.

Your validation rules should reflect the purpose of each scenario.

Consider validating:

  • Required column names.

  • Empty values.

  • Duplicate scenario names.

  • Unexpected data types.

  • Invalid values.

  • Duplicate identifiers.

  • Unexpected column counts.

  • Data that violates business rules.

For a small test suite, basic validation may be enough.

For a large framework, you can create a dedicated validation function or use a schema-validation library.

The important point is that malformed test data should produce a clear error instead of causing confusing browser failures later.

CSV Test Data and Parallel Execution

Playwright can execute tests in parallel.

This can make a test suite faster, but it also introduces a data-management challenge.

Imagine two tests using the same account.

Test A changes the account's password.

Test B tries to log in using the old password.

The tests may interfere with each other.

The problem is not the CSV format. The problem is shared mutable state.

To reduce conflicts:

  1. Use separate accounts when the scenarios modify account state.

  2. Generate unique identifiers when records must be unique.

  3. Reset the test environment where appropriate.

  4. Avoid relying on a previous test's actions.

  5. Use controlled test fixtures for reusable setup and cleanup.

If your project needs reusable setup, review the PlaywrightMasters Playwright Fixtures Guide.

CSV vs JSON: Which Should You Choose?

Choose CSV when your data naturally fits into rows and columns.

For example, a login dataset may contain:

Username

Password

Expected result

userA

passwordA

success

userB

passwordB

failure

Choose JSON when your data contains nested structures or related groups of values.

For example, a customer record might contain a name, contact details, shipping address, and a list of products.

Both formats can support data-driven Playwright tests.

The decision should depend on readability, validation requirements, the people maintaining the data, and the complexity of the records.

Common Mistakes When Reading CSV Data in Playwright

1. Splitting every line using commas

A simple split(',') does not correctly handle all valid CSV structures.

Use a suitable parser for files that may contain quoted commas or other special characters.

2. Ignoring column headers

If your test expects searchTerm but the CSV contains searchterm, the property may not be available under the expected name.

Validate column headers explicitly.

3. Treating every empty field as an error

Some tests intentionally require empty inputs.

Validate fields according to the scenario instead of rejecting every empty value.

4. Using unclear scenario names

A meaningful test name helps identify the failed scenario.

Avoid generic names such as Row 1 unless the report also clearly identifies the associated test data.

5. Storing real passwords in CSV files

CSV files can expose sensitive information if committed to Git or shared carelessly.

Use synthetic credentials for ordinary test scenarios and secure secret management for any sensitive configuration.

6. Assuming that more rows always mean better coverage

A dataset with 1,000 nearly identical rows may be less useful than a smaller dataset covering distinct business scenarios.

Choose test data that adds meaningful coverage.

7. Forgetting to adapt the locators

The example uses accessible labels and button names.

Your application may have different labels or controls. Use locators that match the actual interface.

8. Ignoring the test environment

A test can fail because the application is unavailable, the data was not seeded, or the expected result changed.

Verify the environment before diagnosing the problem as a Playwright issue.

Frequently Asked Questions

Can Playwright read CSV files directly?

Playwright Test does not provide a dedicated built-in CSV parser. You can read files using Node.js file-system APIs and parse CSV data using a suitable library.

Which library can I use to read CSV files in Playwright?

You can use a library such as csv-parse to parse CSV files. It supports common CSV structures, including quoted fields and commas inside quoted values.

Can I use CSV data for login testing?

Yes. A CSV file can store usernames, passwords for synthetic test accounts, and expected outcomes. Keep real credentials out of source-controlled test-data files.

Can one CSV file create multiple Playwright tests?

Yes. You can read the CSV rows into an array and declare a separate Playwright test for each record.

Should I use CSV or JSON for Playwright test data?

CSV is convenient for flat tabular data. JSON is more suitable for nested objects and complex structures. Choose the format that best matches the data.

How do I debug a failing CSV-driven test?

Check the parsed row, the test name, the actual input, the locator, and the expected result. Also confirm that the application environment is available and contains the required data.

Can CSV-driven tests run in parallel?

Yes. Playwright can run separate tests in parallel, but you must ensure that the data and resources used by those tests do not conflict.

Conclusion

CSV files provide a practical way to manage tabular test data in Playwright.

With a CSV parser, a reusable data-reading helper, and parameterized test declarations, you can keep test inputs separate from automation logic.

Start with a small CSV file, validate its columns, use meaningful scenario names, and verify actual application behavior.

As your framework grows, consider adding runtime data validation, independent test accounts, reusable fixtures, and a clear test-data management strategy.

A well-designed CSV test suite is not just a spreadsheet connected to a browser. It is a structured collection of test scenarios that helps you verify application behavior consistently.

For your next step, explore the PlaywrightMasters Playwright Framework Guide and Playwright Fixtures Guide.


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