Data-driven testing is a powerful automated testing technique. It lets you run the same test scripts multiple times with different input values. This approach is useful for testing your app with different data sets. This blog will explore how to use data-driven testing in Playwright with TypeScript. We will focus on three things. First, using data files to drive tests. Second, parameterizing tests with different data sets. Third, managing test data efficiently.
Using Data Files to Drive Tests
The first step in data-driven testing is to organize your test data. You can use various formats like JSON, CSV, or even Excel files to store your test data. For simplicity, we’ll use JSON files in this example.
Example 1: JSON Data File
Step 1: Create a JSON Data File
Create a JSON file, say testData.json, and populate it with test data:
[
{"username": "user1", "password": "password1"},
{"username": "user2", "password": "password2"}
]
Step 2: Read the JSON Data File in Your Test Script
Use Node.js’s built-in fs module to read the JSON file:
import * as fs from 'fs';
const data = JSON.parse(fs.readFileSync('testData.json', 'utf-8'));
Example 2: CSV Data File
Step 1: Create a CSV Data File
Create a CSV file named testData.csv with the following content:
username, password
user1, password1
User2, password2
user3, password3
Step 2: Read the CSV Data File in Your Test Script
To read and parse the CSV file in your TypeScript test script, you can use the csv-parse library by running:
npm install csv-parse
Next, use the following code to read and parse the CSV file:
import * as fs from 'fs'
import { parse } from 'csv-parse/sync'; const csvData = fs.readFileSync('testData.csv', 'utf-8');
const records = parse(csvData, {
columns: true,
skip_empty_lines: true
});
Parameterizing Tests with Different Data Sets
With the data loaded from either JSON or CSV, the next step is to parameterize your tests. The playwright offers a simple way to do this. Use a loop to iterate over the data sets.
records.forEach((user) => {
test(`Login test for ${user.username}`, async ({ page }) => {
await page.goto('https://example.com/login');
await page.fill('#username', user.username);
await page.fill('#password', user.password);
await page.click('#loginButton');
const welcomeMessage = await page.locator('#welcomeMessage').textContent();
expect(welcomeMessage).toContain(`Welcome ${user.username}`);
});
}); In this example, we loop through each user in the data array (from JSON or CSV). We create a separate test case for each one. This way, each test runs with a different set of data, ensuring comprehensive coverage.
Managing Test Data Efficiently
Efficiently managing test data is key to a scalable, maintainable test suite. Here are some best practices:
- Segregate Test Data: Store test data separately from your test scripts. This separation makes it easier to update data without modifying the tests.
- Use Environment-Specific Data: If your app has different environments, your test data must be specific to each one. This approach helps in testing different scenarios without hardcoding values.
- Data Generation Scripts: For large, complex datasets, write scripts to generate test data. This method is particularly useful for performance testing.
- Version Control: Store your test data files and scripts in version control. This practice ensures that changes to test data are tracked and can be reverted if necessary.



Example: Environment-Specific Data
Use environment variables to load different data files based on the environment.
const env = process.env.TEST_ENV || 'dev';
const data = JSON.parse(fs.readFileSync(`testData.${env}.json`, 'utf-8'));
You can have different JSON or CSV files for different environments such as testData.dev.json, testData.staging.csv, and testData.prod.json.
Example: Data Generation Script
import { faker } from '@faker-js/faker';
import * as fs from 'fs';
interface User {
username: string;
password: string;
}
const generateTestData = (numUsers: number) => {
const users: User[] = [];
for (let i = 0; i < numUsers; i++) {
users.push({
username: faker.internet.userName(),
password: faker.internet.password()
});
}
fs.writeFileSync('generatedTestData.json', JSON.stringify(users, null, 2));
};
generateTestData(10); In this script, we use the Faker library to generate random user data and save it to a JSON file. This approach gives you fresh data for each test run. It reduces the chances of data collisions.
Also, consider using libraries like chance.js or randomatic. They can generate complex data structures if your tests need them. This flexibility lets you create diverse, realistic data sets. They can greatly improve your tests’ robustness.
Conclusion
Data-driven testing in Playwright with TypeScript allows robust and flexible test automation. Using data files like JSON and CSV to drive tests and parameterizing them with different data sets will ensure good coverage. Also, managing test data efficiently will boost maintainability. This approach not only improves the reliability of your tests but also makes it easier to identify and fix issues in your application. Start using data-driven testing in your Playwright projects. It will take your test automation to the next level.
With these practices, you can scale your testing efforts. This will ensure your app works well in all scenarios and with all data. Whether you choose JSON, CSV, or another format, the key is to select the one that best fits your team’s workflow and project needs.
















