Playwright Tutorial - automate downloads using Playwright?
While automating the test cases, handling downloads and verifying it is always tricky. Using the playwright we can download the files and handle the download event. For every file download, page.on('download') event gets emitted. Using the download object from the event you can obtain the download URL, Path, file name, and payload stream and verify it.
I have created a YouTube video in the "software testing tips and tricks" channel where I have explained how to download a sample file and store it on at specific path with the code. Also, I will explain the code and the documentation with a few tips and tricks around.Here is the typescript code to handle downloads using the playwright -
test('Handle File Downloads', async({context})=>{
const page = await context.newPage();
await page.goto("https://filesamples.com/formats/jpeg")
// Start waiting for download before clicking. Note no await.
const downloadPromise = page.waitForEvent('download');
await page.getByRole('link', { name: 'Download' }).nth(1).click();
const download = await downloadPromise;
// Wait for the download process to complete and save the downloaded file somewhere.
await download.saveAs('./tests/' + download.suggestedFilename());
});
As suggested in Playwright document, If you have no idea what initiates the download, you can still handle the event -
page.on('download', download => download.path().then(console.log));
All Playwright Tutorial Posts -
- Setup NodeJS playwright and run the first script
- Learn basic automation with Playwright - with code
- Expect and Auto-waits in Playwright
- How to debug the playwright script?
- How to compare screenshots using Playwright?
- Best Practices with Playwright automation
- Playwright Tutorial - Handle Multiple Tabs with Playwright
No comments