Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      How To Prevent WordPress SQL Injection Attacks

      June 12, 2025

      Java never goes out of style: Celebrating 30 years of the language

      June 12, 2025

      OpenAI o3-pro available in the API, BrowserStack adds Playwright support for real iOS devices, and more – Daily News Digest

      June 12, 2025

      Creating The “Moving Highlight” Navigation Bar With JavaScript And CSS

      June 11, 2025

      Surface Pro 11 with Snapdragon X Elite drops to lowest price ever

      June 12, 2025

      With WH40K Boltgun and Dungeons of Hinterberg, this month’s Humble Choice lineup is stacked for less than $12

      June 12, 2025

      I’ve been loving the upgrade to my favorite mobile controller, and there’s even a version for large tablets

      June 12, 2025

      Copilot Vision just launched — and Microsoft already added new features

      June 12, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      Master Data Management: The Key to Improved Analytics Reporting

      June 12, 2025
      Recent

      Master Data Management: The Key to Improved Analytics Reporting

      June 12, 2025

      Salesforce Lead-to-Revenue Management

      June 12, 2025

      React Native 0.80 – React 19.1, JS API Changes, Freezing Legacy Arch and much more

      June 12, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Surface Pro 11 with Snapdragon X Elite drops to lowest price ever

      June 12, 2025
      Recent

      Surface Pro 11 with Snapdragon X Elite drops to lowest price ever

      June 12, 2025

      With WH40K Boltgun and Dungeons of Hinterberg, this month’s Humble Choice lineup is stacked for less than $12

      June 12, 2025

      I’ve been loving the upgrade to my favorite mobile controller, and there’s even a version for large tablets

      June 12, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Running Multiple Test Cases from a CSV File Using Playwright and TypeScript.

    Running Multiple Test Cases from a CSV File Using Playwright and TypeScript.

    June 11, 2025

    In the world of automated testing, maintaining flexibility and scalability is crucial—especially when it comes to validating functionality across multiple data inputs. Data-driven testing enables QA professionals to decouple test scripts from the input data, allowing the same test flow to run with multiple sets of inputs.

    This tutorial explains how to set up data-driven tests in Playwright using TypeScript, where external CSV files provide varying input data for each scenario.

    This approach is highly effective for validating login scenarios, form submissions, and any functionality that depends on multiple sets of data.

    Why Use Data-Driven Testing?

    Data-driven testing provides several benefits:

    • Reduced Code Duplication: Instead of writing multiple similar tests, a single test reads various inputs from an external file.
    • Improved Maintainability: Test data can be modified independently of the test logic.
    • Scalability: Enables easier scaling of testing across a wide range of input combinations.

    When working with TypeScript and Playwright, using CSV files for test input is a natural fit for structured test cases, such as form validation, login testing, and e-commerce transactions.

    Setting Up the Project

    To get started, make sure you have a Playwright and TypeScript project set up. If not, here’s how to initialize it:

    npm init -y

    npm install -D @playwright/test

    npx playwright install

    Enable TypeScript support:

    npm install -D typescript ts-node

    Create a basic tsconfig.json:
    
    {
    
      "compilerOptions": {
    
        "target": "ES6",
    
        "module": "commonjs",
    
        "strict": true,
    
        "esModuleInterop": true,
    
        "outDir": "dist"
    
      },
    
      "include": ["*.ts"]
    
    }

     

    Now, install a CSV parsing library:

    npm install csv-parse

    Creating the CSV File

    We’ll begin by setting up a basic loginData.csv file containing sample login credentials.

    username, password

    user1,password1

    user2,password2

    invalidUser,wrongPass

    Save it in your project root directory.

    Reading CSV Data in TypeScript

    Create a helper function, readCSV.ts, to parse CSV files:

    import fs from 'fs';
    
    import { parse } from 'csv-parse';
    
    export async function loadCSV(fileLocation: string): Promise<Record<string, string>[]> {
    
      return new Promise((resolve, reject) => {
    
        const results: Record<string, string>[] = [];
    
        fs.createReadStream(fileLocation)
    
          .pipe(parse({ columns: true, skip_empty_lines: true }))
    
          .on('readable', function () {
    
            let row;
    
            while ((row = this.read()) !== null) {
    
              results.push(row);
    
            }
    
          })
    
          .on('end', () => resolve(results))
    
          .on('error', (error) => reject(error));
    
      });
    
    }

    Writing the Data-Driven Test in Playwright

    Now, let’s write a test that uses this CSV data. Create a file named login.spec.ts:

    import { test, expect } from '@playwright/test';
    
    import { readCSV } from './readCSV';
    
    
    
    
    test.describe('Data-Driven Login Tests', () => {
    
      let testData: Array<{ username: string; password: string }>;
    
    
    
    
      test.beforeAll(async () => {
    
        testfile = await readCSV('./loginData.csv');
    
      });
    
    
    
    
      for (const data of testfile || []) {
    
        test(`Log in attempt with ${data.username}`, async ({ page }) => {
    
          await page.goto('https://example.com/login');
    
          await page.fill('#username', data.username);
    
          await page.fill('#password', data.password);
    
          await page.click('button[type="submit"]');
    
    
    
    
          // Adjust this check based on expected outcomes
    
          if (data.username.startsWith('user')) {
    
            await expect(page).toHaveURL(/dashboard/);
    
          } else {
    
             expect(page.locator('.error-text')).toBeVisible();
    
          }
    
        });
    
      }
    
    });

    The approach reads each row from the CSV and generates individual test cases dynamically, using the data from each entry as input parameters.

    Best Practices

    • Separate Test Data from Logic: Always keep your data files separate from test scripts to simplify maintenance.
    • Validate Test Inputs: Ensure CSV files are clean and correctly formatted.
    • Parameterize Conditions: Adjust validation logic based on the nature of test data (e.g., valid vs. invalid credentials).

    Conclusion

    Using CSV-based data-driven testing with Playwright and TypeScript offers a powerful way to scale test coverage without bloating your codebase. It’s ideal for login scenarios, input validation, and other repetitive test cases where only the data varies.

    By externalizing your data and looping through test scenarios programmatically, you can reduce redundancy, improve maintainability, and support continuous delivery pipelines more effectively.

    As your application grows, this strategy will help ensure that your test suite remains efficient, readable, and scalable.

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleConvert Special Characters to ASCII with Laravel’s Str::transliterate Method
    Next Article Professor Rita McGrath on Leading in Times of Uncertainty

    Related Posts

    Security

    Apache Tomcat Under Attack: Massive Brute-Force Campaign Targets Manager Interfaces

    June 13, 2025
    Security

    Warning: Discontinued Amazon Cloud Cam Has Vulnerability (CVE-2025-6031), Exposing Your Network

    June 13, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    Memorial Day 2025 Deals

    News & Updates

    CVE-2024-12533 – Apache Phoenix SecureCore Technology Input Validation Bypass

    Common Vulnerabilities and Exposures (CVEs)

    Droip: The Next Big Revolution in WordPress – Redefining No-Code Web Building

    News & Updates

    Buy a Samsung Odyssey G9 gaming monitor on sale and get a second screen for free

    News & Updates

    Highlights

    CVE-2025-1533 – ASUS Armoury Crate App Stack Buffer Overflow

    May 12, 2025

    CVE ID : CVE-2025-1533

    Published : May 12, 2025, 10:15 a.m. | 46 minutes ago

    Description : A stack buffer overflow has been identified in the AsIO3.sys driver. This vulnerability can be triggered by input manipulation, may leading to a system crash (BSOD) or other potentially undefined execution.
    Refer to the ‘Security Update for Armoury Crate App’ section on the ASUS Security Advisory for more information.

    Severity: 0.0 | NA

    Visit the link for more details, such as CVSS details, affected products, timeline, and more…

    CVE-2024-51453 – IBM Sterling Secure Proxy Directory Traversal Vulnerability

    May 28, 2025

    October is the Cyber Security Month: stats, events and advice

    April 9, 2025

    Rilasciato Auto-cpufreq 2.6: Ottimizzazione avanzata della CPU su GNU/Linux

    April 27, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.