Practical Automation Examples

Introduction

CSV (Comma-Separated Values) files are widely used in automation testing because they provide a simple and organized way to store test data. Instead of hardcoding values inside test scripts, automation engineers can keep usernames, passwords, search keywords, product details, API request data, and expected results in CSV files.

Node.js makes it easy to read, write, and process CSV files using packages such as csv-parser and csv-writer.

For automation engineers, CSV files are an essential part of data-driven testing, where the same test script is executed multiple times with different sets of input data.

In this tutorial, we’ll explore several practical examples that demonstrate how CSV files are used in real-world automation projects.


Example 1: Read Login Credentials

Suppose users.csv contains:

username,password
admin,admin123
john,password1
alice,password2

Read the CSV file.

const fs = require("fs");
const csv = require("csv-parser");

const users = [];

fs.createReadStream("users.csv")
    .pipe(csv())
    .on("data", (row) => {
        users.push(row);
    })
    .on("end", () => {
        console.log(users);
    });

Sample Output

[
  { username: 'admin', password: 'admin123' },
  { username: 'john', password: 'password1' },
  { username: 'alice', password: 'password2' }
]

Example 2: Perform Data-Driven Login Testing

const fs = require("fs");
const csv = require("csv-parser");

fs.createReadStream("users.csv")
    .pipe(csv())
    .on("data", (user) => {
        console.log(
            `Testing login for ${user.username}`
        );
    });

Sample Output

Testing login for admin
Testing login for john
Testing login for alice

Example 3: Read Product Data

Suppose products.csv contains:

id,product,price
1,Laptop,75000
2,Mouse,800
3,Keyboard,1500
const fs = require("fs");
const csv = require("csv-parser");

fs.createReadStream("products.csv")
    .pipe(csv())
    .on("data", (row) => {
        console.log(row.product);
    });

Sample Output

Laptop
Mouse
Keyboard

Example 4: Validate Employee Records

Suppose employees.csv contains:

id,name,department
1,John,HR
2,Alice,IT
3,Bob,Finance
const fs = require("fs");
const csv = require("csv-parser");

fs.createReadStream("employees.csv")
    .pipe(csv())
    .on("data", (employee) => {
        if (employee.department === "IT") {
            console.log(employee.name);
        }
    });

Sample Output

Alice

Example 5: Export Test Results to a CSV File

const createCsvWriter =
    require("csv-writer").createObjectCsvWriter;

const csvWriter = createCsvWriter({
    path: "results.csv",
    header: [
        { id: "test", title: "TEST" },
        { id: "status", title: "STATUS" }
    ]
});

csvWriter.writeRecords([
    {
        test: "Login Test",
        status: "Passed"
    },
    {
        test: "Search Test",
        status: "Passed"
    }
]).then(() => {
    console.log("Results exported.");
});

Sample Output

Results exported.

Generated results.csv

TEST,STATUS
Login Test,Passed
Search Test,Passed

Example 6: Save API Response Data

const createCsvWriter =
    require("csv-writer").createObjectCsvWriter;

const csvWriter = createCsvWriter({
    path: "api-results.csv",
    header: [
        { id: "endpoint", title: "ENDPOINT" },
        { id: "status", title: "STATUS" }
    ]
});

csvWriter.writeRecords([
    {
        endpoint: "/users",
        status: 200
    },
    {
        endpoint: "/orders",
        status: 201
    }
]).then(() => {
    console.log("API results saved.");
});

Sample Output

API results saved.

Example 7: Count Total Records

const fs = require("fs");
const csv = require("csv-parser");

let count = 0;

fs.createReadStream("employees.csv")
    .pipe(csv())
    .on("data", () => {
        count++;
    })
    .on("end", () => {
        console.log(
            `Total Records: ${count}`
        );
    });

Sample Output

Total Records: 3

Example 8: Filter Records

Display employees who belong to the HR department.

const fs = require("fs");
const csv = require("csv-parser");

fs.createReadStream("employees.csv")
    .pipe(csv())
    .on("data", (row) => {
        if (row.department === "HR") {
            console.log(row);
        }
    });

Sample Output

{ id: '1', name: 'John', department: 'HR' }

Real-World Example

Generate a CSV report after automation execution.

const createCsvWriter =
    require("csv-writer").createObjectCsvWriter;

const csvWriter = createCsvWriter({
    path: "execution-report.csv",
    header: [
        { id: "scenario", title: "SCENARIO" },
        { id: "result", title: "RESULT" }
    ]
});

const report = [
    {
        scenario: "Login",
        result: "Passed"
    },
    {
        scenario: "Checkout",
        result: "Failed"
    }
];

csvWriter.writeRecords(report)
    .then(() => {
        console.log("Execution report generated.");
    });

Sample Output

Execution report generated.

Framework Integration Examples

Playwright Example

Read test users from a CSV file.

const fs = require("fs");
const csv = require("csv-parser");

fs.createReadStream("users.csv")
    .pipe(csv())
    .on("data", (user) => {
        console.log(user.username);
    });

Selenium Example

Read search keywords.

const fs = require("fs");
const csv = require("csv-parser");

fs.createReadStream("keywords.csv")
    .pipe(csv())
    .on("data", (row) => {
        console.log(row.keyword);
    });

Cypress Example

Read product information.

const fs = require("fs");
const csv = require("csv-parser");

fs.createReadStream("products.csv")
    .pipe(csv())
    .on("data", (row) => {
        console.log(row.product);
    });

API Testing Example

Read API request data.

const fs = require("fs");
const csv = require("csv-parser");

fs.createReadStream("requests.csv")
    .pipe(csv())
    .on("data", (row) => {
        console.log(row.userId);
    });

Data-Driven Testing Example

Execute one test for each employee record.

const fs = require("fs");
const csv = require("csv-parser");

fs.createReadStream("employees.csv")
    .pipe(csv())
    .on("data", (employee) => {
        console.log(
            `Executing test for ${employee.name}`
        );
    });

Common Mistakes

Forgetting to Install Required Packages

Before reading CSV files:

npm install csv-parser

Before writing CSV files:

npm install csv-writer

Using Incorrect Column Names

Incorrect:

console.log(row.employeeName);

If the CSV header is:

name

Use:

console.log(row.name);

Hardcoding Test Data

Avoid writing test data directly inside automation scripts.

Store test data in CSV files so the same script can run with multiple datasets.


Best Practices

  • Store CSV files in dedicated data, fixtures, or reports folders.

  • Use meaningful column headers.

  • Validate CSV data before processing it.

  • Handle file and parsing errors properly.

  • Keep test data separate from automation scripts.

  • Use CSV files for data-driven testing.

  • Generate execution reports in CSV format for easy analysis.

  • Verify generated CSV files after writing them.


Conclusion

CSV files play a vital role in Node.js applications and automation testing. They provide a simple, portable, and efficient way to store structured data for reading, writing, parsing, and exporting.

For automation engineers, CSV files simplify data-driven testing, report generation, API validation, and execution tracking. By combining csv-parser and csv-writer, you can build flexible and maintainable automation frameworks that work with large datasets.

Mastering practical CSV automation examples prepares you to handle real-world testing scenarios with confidence.


Frequently Asked Questions (FAQs)

Why are CSV files widely used in automation testing?

CSV files allow automation engineers to store external test data, making test scripts reusable and supporting data-driven testing.


Which package is commonly used to read CSV files?

The csv-parser package.


Which package is commonly used to write CSV files?

The csv-writer package.


Can I use CSV files with Playwright, Selenium, and Cypress?

Yes. CSV files are commonly used with all major automation frameworks to manage test data and generate reports.


Why should test data be stored in CSV files instead of hardcoding values?

External CSV files make automation scripts easier to maintain, update, and reuse without modifying the source code.


Key Takeaways

  • CSV files are widely used for data-driven testing.

  • Use csv-parser to read and parse CSV files.

  • Use csv-writer to generate CSV reports and export data.

  • Store login credentials, API inputs, and test data in CSV files.

  • Generate execution reports in CSV format for easy analysis.

  • Keep automation scripts separate from test data.

  • Validate CSV data before using it in tests.

  • CSV files are supported by Excel, Google Sheets, and many other applications.

  • CSV file handling is widely used in Playwright, Selenium, Cypress, API testing, and Node.js applications.

  • Mastering CSV automation examples is essential for backend development and professional automation testing.