Handle download in Playwright (Typescript)

Table Of Contents

Overview

Download is an important feature of any website. Playwright does support native API for automate test cases related to it. In this article, let’s see how to handle download in Playwright (Javascript/Typescript).

Please note that this article will not focus on how to set up a Playwright automation project from beginning. If you do not know how-to, please refer to Playwright doc at here.

How to

Let’s practice a real example as below image. After click to ‘Download sample’ button, a ‘If_You_Wait_1’ .txt file will be downloaded to your local machine.

Handle download in Playwright (tomatoqa.com)

Below is automated test script for this case:

import { test, expect } from '@playwright/test';

test('has title', async ({ page }) => {

  // go to url
  await page.goto('https://demo.nopcommerce.com/if-you-wait-donation');

  // wait for download event before click download button
  const downloadPromise = page.waitForEvent('download');

  // click to download button
  await page.click('a.download-sample-button');

  // wait for download event to complete
  const download = await downloadPromise;

  // assert if name of downloaded file is correct
  const downloadedFile: string = download.suggestedFilename();
  expect(downloadedFile).toEqual('If_You_Wait_1.txt');

  // save downloaded file to the root folder of project
  await download.saveAs('./' + downloadedFile);
});

Quite simple right? Only two methods you need to remember here:

+ download.suggestedFileName(): return the original name of downloaded file

+ download.saveAs(): needs an argument is path of directory where to save the file. Naturally, the file will not be automatically saved in your local machine. Playwright only store the file’s temporary version and it will be deleted after finishing running test case. If you want to store it, you must use this method. It returns a Promise which will be resolved after the file is saved successfully in specified path.

Conclusion

Handle download functionality in Playwright is not complicated. Comparing to its competitor (Selenium), I think it Selenium has recently support more ways for download/upload features. And about downloading PDF file in PDF viewer, Playwright lacks support at this moment. But it is still a quite new tool and will be improved in near future.

Ask me anything