DEV Community

ryanrosello-og
ryanrosello-og

Posted on • Updated on

Use playwright to download files from remote servers

Downloading files from a remote server is often a challenging prospect when it comes to incorporating the process into an automated test. This task can be easily performed by using Playwrights' native REST API helper library.

The example below is a typical pseudo Download button with a href pointing to location of a file on a remote server.

Typical download button

There are numerous ways of tackling this issue using Playwright. Our example below will utilise Playwrights' ability to perform REST calls.

Firstly, you'll need to fs



import * as fs from 'fs/promises'  // For saving the file contents to disk


Enter fullscreen mode Exit fullscreen mode

Within your test, define the baseUrl and the resource path of the file for download.



const baseUrl = 'https://www.tesla.com/'
const resource = 'ns_videos/2021-tesla-impact-report.pdf'


Enter fullscreen mode Exit fullscreen mode

Simply invoke the get method from the API testing helper



const getResp = await page.context().request.get(`${baseUrl}${resource}`)


Enter fullscreen mode Exit fullscreen mode

The response body will be a buffer type. We can save this raw content into a file using the standard fs library. In the example below, I opted to include a random timestamp to the downloaded file. This is entirely optional, your implementation may vary.



let responseBuffer = await getResp.body()
await fs.writeFile(`${new Date().valueOf()}_downloaded_pdf_from_tesla.pdf`, responseBuffer, 'binary')


Enter fullscreen mode Exit fullscreen mode

When the test is executed, the downloaded file (pdf in this example) will appear on your local disk, like so …

File downloaded to the root of the project

Downloading the file directly into the project root folder may not be ideal in most scenarios. Let us make one more change to our test and output the file into a different directly.

Add testInfo to the test definition:



test('able to download a remote file to disk', async ({ page }, testInfo) => {


Enter fullscreen mode Exit fullscreen mode

Modify the download path to use the output path provided by the testInfo object.



const fileName = `${new Date().valueOf()}_downloaded_pdf_from_tesla.pdf`
const downloadPath = testInfo.outputPath(fileName)
await fs.writeFile(downloadPath, responseBuffer, 'binary')


Enter fullscreen mode Exit fullscreen mode

Rerunning the test will result in the downloaded file being persisted within the test-results folder:

File saved into the test-results folder

The final solution:

Top comments (0)