QA Graphic

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.

 

Comments

Add Your Comments

Name:
Comment:

 

About

Welcome to Playwright Tips and Tricks, your go-to resource for mastering the art of web automation and testing with Playwright! Whether you're a seasoned developer looking to streamline your workflows or a curious beginner eager to dive into the world of browser automation, this blog is designed with you in mind. Here, I'll share a treasure trove of practical insights, clever hacks, and step-by-step guides to help you harness the full power of Playwright - a modern, open-source tool that's revolutionizing how we interact with web applications.

Schedule

Monday 28 Media
Tuesday 29 QA
Wednesday 30 Pytest
Thursday 1 PlayWright
Friday 2 Macintosh
Saturday 3 Internet Tools
Sunday 4 Misc