Playwright Create tests via a CSV file

Profile picture for user arilio666

In this article, let's discuss how to read the CSV file and create a test using the CSV file data.

Table of Contents

  1. Sample CSV Data
  2. Read CSV Data
  3. Video Tutorial

Sample CSV Data

Our CSV file with the name users.csv contains the following data.

test_caseusernamepassword
1ram12345
2sham24680

Read CSV Data

Let's read and print this data in the console.

Step 1: Install CSV Parse Module

npm install --save csv-parse

Step 2: Import Required Libraries

// import fs module to interact with file system
import fs from 'fs';

// import path module 
// it provides utilities for working with file and directory paths
import path from 'path';

// converting CSV text input into arrays or objects
// We are using sync API which is good for small data
// Read about others API here https://csv.js.org/parse/api/
import { parse } from 'csv-parse/sync';

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

Step 3: Store CSV Data in a variable

const records = parse(fs.readFileSync(path.join(__dirname, 'users.csv')), {
  columns: true,
  skip_empty_lines: true
});
  • The readFileSyn function blocks other parallel processes until the current file reading process is complete. 
  • The path.join() method concatenates all given path segments using the appropriate platform-specific separator as a delimiter, and then normalizes the resulting path. 
    The __dirname property retrieves the current working directory. 
  • The columns option should be set to true if the first line of the file contains column names. 
  • If the file contains empty lines, you can skip them using the skip_empty_lines option. 
  • By default, the delimiter value is a comma, but you can set any other delimiter using the delimiter option. To view all available options, please refer Node CSV Parse Options

Step 4: Iterate Over CSV Data

for (const record of records) {
  test(`Test Case: ${record.test_case}`, async ({ page }) => {
    console.log(record.test_case, record.username, record.password);
  });
}

While iterating for the loop, we are creating new test cases with each iteration. In the test result, two test cases are created with the name Test Case and test_case column value from the CSV file.

Playwright Read CSV File In console below data will be printed.

1 ram 12345
2 sham 24680

Code:

import fs from 'fs';
import path from 'path';
import { parse } from 'csv-parse/sync';
import { test } from '@playwright/test';

const records = parse(fs.readFileSync(path.join(__dirname, 'users.csv')), {
  columns: true,
  skip_empty_lines: true
});

for (const record of records) {
  test(`Test Case: ${record.test_case}`, async ({ page }) => {
    console.log(record.test_case, record.username, record.password);
  });
}

Video Tutorial: Playwright Read CSV