Tips for uploading files in filepicker with protractor

https://i.sstatic.net/noq46.png

Here's a snippet of HTML code you might find useful:

<input type="file" class="fileUploadInput" name="fileUpload" id="fileUploadInput" accept="application/msword,application/pdf,text/plain,application/rtf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.oasis.opendocument.formula" multiple="multiple" title="Choose File">

In the following code snippet, I use a method to upload a file through Protractor. However, even though there are no errors thrown, the file isn't being uploaded and the pop-up window isn't closing as expected:

 browser.wait(function(){
            return element(by.id('.filepicker_dialog_container')).isPresent();
        }).then(function() {
            browser.driver.switchTo().frame('.filepicker_dialog');
        }).then(function(){
            var fileToUpload = '/home/raghavendra/Desktop/f0657c76d96b9ddab5562b8391297dbbb01488fec4e79a4c13195aea.doc';
            var absolutePath = protractor.basePath.resolve(__dirname, fileToUpload);
            $("#fileUploadInput").sendKeys(absolutePath);
});

Below is the complete code showcasing how I successfully handle file uploads within a Protractor test:

  var path = require('path');
var ptor = browser,
    driver = browser.driver;

describe('Test Suite for Uploading Files', function() {

    it('Click on the filepicker icon and upload a document', function () {


        $('.icon-people').click();
        browser.sleep(5000);
        browser.driver.findElement(By.xpath('/html/body/div[4]/div/ng-view/div/div/div[2]/' +
                                            'section/div/div/div[1]/form/div[2]/input')).sendKeys(group_name);
        browser.sleep(5000);
        element.all(by.css('.btn.btn-main')).click();
        browser.sleep(5000);

        browser.wait(function(){
             return element(by.id('filepicker_dialog')).isPresent();
        })
            .then(function(){
                ptor.switchTo().frame('filepicker_dialog');
            })

            .then(function(){
                 var fileToUpload = '/home/raghavendra/Desktop/50_resumes/f0657c76d96b9ddab5562b8391297dbbb01488fec4e79a4c13195aea.doc';
                 var absolutePath = path.resolve(__dirname, fileToUpload);
                 driver.findElement(By.id('fileUploadInput')).sendKeys(absolutePath);
            })

            .then(function(){
                ptor.switchTo().defaultContent();
            })

            .then(function(){
                browser.wait(function(){
                    var deferred = protractor.promise.defer();
                    element(by.id('filepicker_dialog')).isPresent()
                        .then(function(present){
                            deferred.fulfill(!present);
                        });
                    return deferred.promise;

                });
            });
    });
})

If you encounter any issues or have any questions, please let me know.

Answer №1

Avoid clicking on the "Choose File" button as it will trigger a browser dialog box that is beyond the control of the selenium webdriver.

Instead, input the file path directly to upload:

$("#fileUploadInput").sendKeys("/absolute/path/to/file");

For your specific scenario, follow these steps:

var EC = protractor.ExpectedConditions;
var picker = element(by.id('.filepicker_dialog_container'));

browser.wait(EC.presenceOf(picker), 5000);
browser.switchTo().frame($('.filepicker_dialog'));

var fileToUpload = '/home/username/Desktop/f0657c76d96b9ddab5562b8391297dbbb01488fec4e79a4c13195aea.doc';
var absolutePath = protractor.basePath.resolve(__dirname, fileToUpload);
$("#fileUploadInput").sendKeys(absolutePath);

Answer №2

This block of code is functioning correctly:

const fileHandler = require('file-handler');
const browserInstance = browser,
    webDriver = browser.driver;

describe('Managing different roles in Hirealchemy', function() {

    it('Action upon clicking the filepicker icon', function () {


        $('.icon-people').click();
        browser.sleep(5000);
        browser.driver.findElement(By.xpath('/html/body/div[4]/div/ng-view/div/div/div[2]/' +
                                            'section/div/div/div[1]/form/div[2]/input')).sendKeys(group_name);
        browser.sleep(5000);
        element.all(by.css('.btn.btn-main')).click();
        browser.sleep(5000);

        browser.wait(function(){
             return element(by.id('filepicker_dialog')).isPresent();
        })
            .then(function(){
                browserInstance.switchTo().frame('filepicker_dialog');
            })

            .then(function(){
                 var fileToUpload = '/home/raghavendra/Desktop/50_resumes/f0657c76d96b9ddab5562b8391297dbbb01488fec4e79a4c13195aea.doc';
                 var absolutePath = fileHandler.resolvePath(__dirname, fileToUpload);
                 webDriver.findElement(By.id('fileUploadInput')).sendKeys(absolutePath);
            })

            .then(function(){
                browserInstance.switchTo().defaultContent();
            })

            .then(function(){
                browser.wait(function(){
                    var deferred = protractor.promise.defer();
                    element(by.id('filepicker_dialog')).isPresent()
                        .then(function(present){
                            deferred.fulfill(!present);
                        });
                    return deferred.promise;

                });
            });
    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Rendering an element in React Router Dom based on specific conditions

Starting a new project with the latest version of react-router-dom and following their recommendation to use createBrowserRouter. The goal is to display a different header based on the path parameters. Currently, I have set up an optional path parameter: ...

Guide to creating standalone Express middleware that can interact with the raw request body

Can anyone help me with writing an Express middleware that can access the raw request body without affecting other handlers or middlewares? I want to achieve something like this: const middleware = [ express.raw({ type: '*/*' }), (req, res, n ...

Disabling the scrollbar in Selenium screenshots

When using Chromedriver to capture screenshots of webpages, my code effectively does the job. However, I am now facing an issue with removing the unsightly scrollbars from the image. Is it feasible to inject CSS into the webpage in order to achieve this? W ...

AngularJS routing not rendering the correct view

I'm encountering a routing problem with my AngularJS/ExpressJS application. The issue is that login.ejs and signup.ejs are partial views, while welcome.ejs serves as the main template. The intention is for these views to load in a ui-view container wi ...

Dealing with an empty request.FILES using FileUploadParser in Django Rest Framework and Angular file upload technique

Uploading files in an angular view can sometimes be tricky, especially when using templates. The code snippet below shows how to upload multiple and single files using Angular File Upload library. Multiple <input type="file" name="file" nv-file-select= ...

I find myself perplexed when it comes to understanding smoke tests in the realm of

After doing some research, I understand the concept of a smoke test, but I'm having trouble grasping the real-world application. If someone could provide me with a practical example or use case, it would be immensely helpful. I am particularly confu ...

What is the best way to retrieve information from an Array within a JSON Object?

I currently have a Json object called FriendJson, which contains an array field named friends. This is the Json Object: [ { "id": 4, "updated": "2023-01-07T22:06:23.929206Z", "created": "2023-01-0 ...

Using V-model binding in Vue always resets the content of text inputs

I am facing an issue with a Text Input that is filled based on a string stored in cookies, similar to a Remember me feature. When I bind the value of the input to the cookie using :value, I am unable to type a new value even if there is no cookie being sto ...

Pass a bespoke object back to the GraphQL resolver

In my Node-Express backend server with GraphQL setup, I am working on providing a custom object as output for a GraphQL resolver. The usual Sequelize approach hasn't worked for me in this case, so I'm exploring new methods. const RootQueryType = ...

Tips for managing open and closed components within a React accordion and ensuring only the clicked component is opened

Unique Accordion component: const CustomAccordion = (props: AccordionProps) => { const { label, levels, activeId, id } = props const [isExpand, setIsExpand] = useState(false) const onPress = useEvent(() => { setIsExpand( ...

Tips for utilizing AJAX to send data from a specific row

<table> <tr data-id="1"> <input type="text" name="name_1" value="abc"> <input type="text" name="value_1" value="1"> <a href="load_edit_row(this)">Edit</a> </tr> <tr data-id="2"> <input t ...

My loop encountered an 'Undefined' error while attempting to retrieve an object from a JSON file

Hey everyone, I could use some help with a problem I'm having in my for loop. The issue is that I keep getting an "undefined" word in the output of my loop. I am trying to retrieve objects from a JSON file and the loop itself seems to be working corre ...

Add a trash can or delete icon within every row of a table using Vue.js

I am new to vue.js and I'm struggling to implement a trash icon in each row of a table for deleting rows. Additionally, I'm trying to make the input of a cell act as a dropdown menu or list within the table rows. I recently came across this scrip ...

Discover the following item using jQuery

Here is some HTML code that I have: <div class="form-group"> <input type="text" class="sequence valid"> </div> <div class="form-group"> <input type="text" class="sequence valid"> </div> <div class="som ...

JavaScript: Transform an Array of Strings into an Array of Objects

Here is an array containing different strings: let myArray : ["AA","BB" , "CC" ...] My goal is to transform it into an array of objects: myArray = [{"id":1 , "value": "AAA"},{"id":2 , "value": "BBB"},{"id":3 , "value": "CCC"}...] I attempted to achiev ...

Can you explain the significance of network activity groupings within the Firebug Net tab?

Can you explain the significance of different splitter lines on the Net tab in Firebug? In this screenshot, line 1 and 2 appear to be grouped together. However, line 3 stands alone. What do these groupings represent? ...

The logout function on the website is experiencing some issues. If you encounter difficulties logging out, try closing the browser and reopening it before attempting

Recently, I created a Python script that automates the process of logging into multiple accounts, collecting currency, and logging out. Everything works smoothly except for one issue - every time the script logs out, it still remains logged in when redirec ...

What is the best way to apply attributes to all titles throughout a webpage?

My goal is to locate all elements on the page that have a title attribute and add a new attribute to each of them. For example: <div title='something 1'></div> <p>Test<div title='something 2'></div></p ...

The autocomplete functionality with ajax is currently malfunctioning

<script> function autocomplet1() { var min_length = 0; // minimum characters to display the autocomplete var keyword = $('#select01').val(); if (keyword.length >= min_length) { $.ajax({ url: 'barcode ...

Challenges with NPM testing

Are there any reported issues with npm on Ubuntu 18.04? Or are there known solutions to the 100:1 error? I am currently enrolled in a course and it's crucial for me to be able to execute code using npm test. Despite multiple attempts at deleting and ...