Download Files Using JavaScript and Selenium: A Step By Step Guide
Harita Ravindranath
Posted On: July 7, 2022
254872 Views
10 Min Read
Downloading files is one of the most popular features utilized by Internet users worldwide. Almost all web applications provide a feature that allows users to download a file from the web page. It has many use cases, from downloading your favorite music or video files to invoices and bank statements.
If you are an automation tester fixated on Selenium automation testing, the chances are that you might run into a requirement of testing a feature around downloading files. While being a powerful tool for performing automated browser testing, Selenium natively doesn’t support download functionality. However, we can easily use Selenium to deal with file download, and this blog explores the exact scenario!
In this Selenium JavaScript tutorial, you will learn how to download files using JavaScript and Selenium WebDriver.
Let’s get started!
TABLE OF CONTENTS
Challenges and Solutions in downloading files with Selenium
Selenium is a popular open-source tool that is used to automate web browsers. Selenium WebDriver comes with an exhaustive list of native functions that allows automation testers to effortlessly execute a wide variety of user interactions on the web application like click, type, drag and drop, etc. But when it comes to automating a feature like downloading files, things are not quite straightforward.
One obstacle that testers face while downloading files with Selenium is that every web browser offers a different UI when downloading a file. Even though there is no easy way to control the browser’s native dialogs by JavaScript, there is a workaround for it.
The solution is to trick the browser profile. By leveraging the browser profile setting, you can download files in Selenium WebDriver without interacting with the download window pop-up.
In this blog on how to download files using JavaScript, let us learn how to write automation test code to download a file using JavaScript and Selenium.
How to download files using JavaScript and Selenium?
We will be automating the following test scenario to download files using JavaScript and Selenium:
Step 1: Go to the website File Download Demo for Automation.
Step 2: Enter data in the textarea.
Step 3: Click the “Generate File” button to generate the text file.
Step 4: Click the “Download” link to download the file.
Prerequisites to download files using JavaScript
Before getting started with coding, ensure that you have the following prerequisites installed in your system to download files using JavaScript and Selenium:
- Install Node.js and NPM.
- Install Eclipse and IntelliJ (or any IDE of your choice).
Installation and basic project setup
In this section of this article on how to download files using JavaScript, I will be explaining briefly how to do a basic project setup for automation testing with Selenium JavaScript. Feel free to skip this section if you already have a working project.
Step 1: Create a project folder in the desired location in your system. Open the folder in your IDE.
Step 2: Initialize the project in this folder. Run the following command.
npm init -y
Step 3: Install the project dependencies. We need to install Selenium WebDriver and browser drivers. Here, I am installing the driver for the Chrome browser.
npm install --save selenium-webdriver chromedriver
With this, the project setup is now completed, and the package.json file is generated in the root folder.
Step 4: To maintain the test cases, create a new folder called tests. We will be storing our test files inside this folder.
My project folder structure now looks like this:
Accelerate JavaScript Automation with Parallel testing. Try LambdaTest Now!
Writing test case to download files using JavaScript
Now, it is time to write the code! For downloading a file using Selenium, we will be making use of the click() method. The automation steps are detailed below:
Step 1: Create a test file testOne.js inside the tests folder.
Step 2: Inside testOne.js, pull all the required functions from node_modules.
1 2 |
const { By, Key, Builder } = require("selenium-webdriver"); require("chromedriver"); |
Step 3: Create a function example(), which will be containing your test script. Feel free to provide any function name of your choice.
1 2 3 |
async function example() { } |
Step 4: Inside the function, let us write our test script using Selenium and JavaScript.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
async function example() { //To wait for browser to build and launch properly let driver = await new Builder().forBrowser("chrome").build(); try { //To go to the test website from the browser with our code. await driver.get("http://demo.automationtesting.in/FileDownload.html"); //To enter data inside the text area await driver .findElement(By.id("textbox")) .sendKeys("I love testing!", Key.RETURN); //To click on "Generate File" button await driver.findElement(By.id("createTxt")).click(); //To click on "Download" link await driver.findElement(By.id("link-to-download")).click(); //Wait for 5s till download is completed await driver.sleep(5000); } catch (e) { console.log("Error Occured:", e.name); } //It is always a safe practice to quit the browser after execution await driver.quit(); } |
To locate the Web Elements, I have made use of the Chrome Developer Tools.
Step 5: Now simply add the function call. The full implementation is given below
node testOne.js
The test starts running and an instance of Chrome browser is instantiated.
The test gets executed successfully and the file is downloaded to your default Downloads folder location.
Pace-up your releases and ship quality products faster. Try LambdaTest Now!
Do you want to learn more about the exciting world of JavaScript automation testing? Deep dive into how Selenium WebDriver with JavaScript can be used for automated testing of web applications with this video tutorial:
How to download files to a specific folder using JavaScript and Selenium?
Rather than downloading into the default Downloads folder, sometimes you might need to download the files to a specific folder location for storing and verifying all the downloads. In this section of this article on how to download files using JavaScript, let us learn how to configure the code to set the browser file Download directory for Chrome driver using Selenium and JavaScript.
Step 1: Make the following two additional imports in our previous code.
1 2 |
const chromeDriver = require("selenium-webdriver/chrome"); const webdriver = require("selenium-webdriver"); |
Step 2: Define Chrome options. Inside setUserPreferences, set your custom download path.
1 2 3 4 |
var options = new chromeDriver.Options(); options.setUserPreferences({ "download.default_directory": "your\download\folder\path", }); |
For example,
1 |
"download.default_directory": "D:\\Test", |
Step 3: Redefine your driver instance.
1 2 3 4 5 |
var driver = new webdriver.Builder() .withCapabilities(webdriver.Capabilities.chrome()) .forBrowser("chrome") .setChromeOptions(options) .build(); |
The full implementation is as shown below.
node testTwo.js
The test gets executed successfully, and the file is downloaded to the specific path mentioned.
If you are a JavaScript developer, this certification will certify your competence as an in-depth, hands-on JavaScript automation pro.
Here’s a short glimpse of the Selenium JavaScript 101 certification from LambdaTest:
How to download files using JavaScript and cloud Selenium Grid?
In the above demo test scenarios, we learned how to download files using JavaScript and Selenium WebDriver to our local systems and execute our tests in the Chrome browser.
However, most Selenium testing projects use online Selenium Grid to achieve cross browser testing and better test coverage to ensure that the test is working fine in all major browser-OS-device combinations.
In this section of this article on how to download files using JavaScript, let us learn how to execute our code in the cloud-based Selenium Grid provided by LambdaTest.
LambdaTest is a cross browser testing platform that provides an online browser farm of 3000+ browser and OS combinations and an online Selenium Grid that you can integrate with your current test project via minimum code changes. LambdaTest scalable cloud infrastructure helps you perform web testing and web application testing across real desktop and mobile browsers. You can execute your JavaScript automation tests instantly on LambdaTest cloud, without worrying about building or maintaining an in-house device lab.
Subscribe to the LambdaTest YouTube channel when you want to catch up with the latest news on automated browser testing, automated UI testing, etc.
Follow along to learn how!
Step 1: Create a free account on LambdaTest and secure your unique username and access key.
Step 2: Inside the test file, define all the required variables for connecting with the Remote Grid like your unique username, access key, grid host, remote grid URL etc.
1 2 3 4 5 6 |
const USERNAME = "YOUR_USERNAME"; //replace with your username const KEY = "YOUR_ACCESSKEY"; //replace with your accesskey const GRID_HOST = "hub.lambdatest.com/wd/hub"; const gridUrl = "https://" + USERNAME + ":" + KEY + "@" + GRID_HOST; |
Step 3: Pass the browser capabilities. You can generate your custom desired capabilities using LambdaTest Capabilities Generator.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var capabilities = { "LT:Options": { user: USERNAME, accessKey: KEY, build: "JavaScript and Selenium Testing", name: "Download File", platformName: "Windows 11", selenium_version: "4.1.0", driver_version: "99.0", }, browserName: "Chrome", browserVersion: "99.0", }; |
Here, I am configuring my test to run in Chrome Browser version 99.0 with Windows 11 OS using the latest Selenium 4.
Step 4: The configuration is completed. Our final code now looks like this.
node testThree.js
The test starts running. Go to the LambdaTest Dashboard to observe the live running status.
Our test got executed successfully. You can analyze the detailed report containing video and logs.
Moreover, you can navigate to the LambdaTest Analytics Dashboard to see test performance metrics. You can see the total number of tests passed or failed from the Test Summary section. You can also see the snapshot of consistent tests from the Test Overview section.
Conclusion
File Download is a common feature offered by most web applications. In this tutorial on how to download files using JavaScript and Selenium, we explored how to write an automation test case for downloading a file using JavaScript and Selenium WebDriver.
Additionally, we explored edge cases like how to download files using JavaScript to a specific folder and how to run our tests using an online Selenium Grid for better test coverage and cross browser testing. I hope this tutorial turned out to be beneficial!
Happy Testing!
Frequently Asked Questions (FAQs)
How do you read a File in JavaScript?
JavaScript enables you to read a file in several ways. The FileReader object is the most flexible. You can instruct it to read a file as an array buffer, a data URL, or text.
Can JavaScript save a file?
JavaScript, as a scripting language, is not directly responsible for saving a file. Therefore, the JavaScript interpreter cannot be instructed to save a file. To save a file, a program that runs on the computer must do so at the command of a programmer. However, a JavaScript program might prompt or direct the user to save a file.
Got Questions? Drop them on LambdaTest Community. Visit now