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.
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
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'
Simply invoke the get
method from the API testing helper
const getResp = await page.context().request.get(`${baseUrl}${resource}`)
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')
When the test is executed, the downloaded file (pdf in this example) will appear on your local disk, like so …
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) => {
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')
Rerunning the test will result in the downloaded file being persisted within the test-results
folder:
Top comments (0)