Get Random Line from a File
Add some variety to your PlayWright tests
In PlayWright, you can easily get the contents of a file to include in a form. This is the getRandomLineFromFile function that I use to open up a local file and get a random line:
async function getRandomLineFromFile(filePath: string): Promise {
try {
// Read file content and split into lines
const fileContent = await fs.readFile(filePath, 'utf8');
const lines = fileContent.split('n').filter(line => line.trim() !== ''); // Remove empty lines
if (lines.length === 0) {
throw new Error('File is empty');
}
// Get random line
const randomIndex = Math.floor(Math.random() * lines.length);
return lines[randomIndex].trim();
} catch (error) {
console.error(`Error reading file: ${error}`);
throw error;
}
}
I would use this to open up a file that has a random sentence to fill in a feedback form. Here's an example PlayWright with TypeScript entry that I would use:
test('Random Feedback Form Test', async ({ page }) => {
const filePath = '/Users/dict/srand.txt';
const randomLine = await getRandomLineFromFile(filePath);
await page.goto('https://www....');
await page.waitForLoadState("networkidle");
await page.getByLabel('name').fill('Chris Ryan');
await page.getByLabel('comment').fill(testText);
....
})
You could also do this to randomize names, locations etc. This is just handy to have when you want to add some variety to a test run.