Upload file to hidden input using protractor and selenium - selenium

I've got a hidden file input field like this:
<input type="file" id="fileToUpload-1827" multiple="" onchange="angular.element(this).scope().setFiles(this)" data-upload-id="1827" class="hidden-uploader">
I'd like to be able to upload files to this. The normal way to do this in protractor would be to do:
ptor.findElement(protractor.By.css('.file-upload-form input')).sendKeys('/path/to/file')
But because the input element isn't visible, I get an error.
I tried:
ptor.driver.executeScript("return $('.file-upload-form input')[0].removeClass('hidden-uploader');").then(function () {
ptor.findElement(protractor.By.css('.file-upload-form input')).sendKeys('hello');
})
But got the error
UnknownError: $(...)[0].removeClass is not a function
It seems ridiculous to have to use executeScript to make an element visible so that I can upload a file, is there a better way? If not, how do I unhide the element?
The full html for the input form is:
<form class="file-upload-form ng-scope ng-pristine ng-valid" ng-if="ajaxUploadSupported">
<strong>Drag files here to upload</strong> or
<label for="fileToUpload-1953">
<div class="btn btn-info select-file-btn">
Click to Select
</div>
</label>
<div>
<input type="file" id="fileToUpload-1953" multiple="" onchange="angular.element(this).scope().setFiles(this)" data-upload-id="1953" class="hidden-uploader">
</div>
</form>

The only way I could find to do this in the end was to use javascript to make the input element visible.
So I have a function unhideFileInputs:
var unhideFileInputs = function () {
var makeInputVisible = function () {
$('input[type="file"]').removeClass('hidden-uploader');
};
ptor.driver.executeScript(makeInputVisible);
}
This contains the function 'makeInputVisible' which is executed in the browser when I call ptor.driver.executeScript(makeInputVisible). Because I know my page contains jQuery I can use the jQuery removeClass method to unhide my file input element.
To see more on how to execute javascript in the browser using webdriver, see the answer to this question (although the answer uses executeAsyncScript rather than executeScript).

To add on user2355213s answer for the more current releases of protractor. ptor is obsolote and instead browser should be used. Also, executeScript() expects a string as parameter. So I ended up using
browser.executeScript('$(\'input[type="file"]\').attr("style", "");');
as my visibility setting was directly applied to the element. Of course, you can also use
browser.executeScript('$(\'input[type="file"]\').removeClass("hidden-uploader");');
depending on your HTML/CSS.

Related

Cypress doesn't find input field (maybe because inside a form?)

Page source (only iFrame part which contains to form i need to fill)
<iframe title="Form 0" id="hs-form-iframe-0" >
#document
<html>
<body>
<form id="hsForm_405e4c3f-98da-4eb1-bd27-c1886a1f811e">
<div>
<label placeholder="Enter your Vorname">Vorname</span>
<div class="input">
<input name="firstname">
</input>
</div>
</div>
</form>
</body>
</html>
</iframe>
Code i tried:
cy.get('#hs-form-iframe-0').its('0.contentDocument').should('exist')
cy.get('input[name="firstname"]').type( 'Smith') //failes as never found. Is the iFrame the cause of it? Of the form?
TLDR The correct way would be to use .find() on the iframe contentWindow.
cy.get('#hs-form-iframe-0').its('0.contentWindow').should('exist')
.its('body').should('not.be.undefined')
.find('input[name="firstname"]').type( 'Smith')
Example from Working with iframes in Cypress
const getIframeWindow = () => {
return cy.get('iframe[data-cy="the-frame"]')
.its('0.contentWindow').should('exist')
.its('body').should('not.be.undefined')
}
cy.getIframeBody().find('#run-button').should('have.text', 'Try it').click()
There are other potential problems, such as delayed loading of the iframe source. The .should('exist') check on the iframe window does not cover all situations, nor does performing visibility checks on the input.
The cypress-iframe package has a lot more checks built in, so it's a safer way to handle iframes.
You have found the iframe and access its contents but then you search for the input at the root of your DOM instead of the iframe. You can continue the chain of commands by removing the second cy.
cy.get('#hs-form-iframe-0')
.its('0.contentDocument')
.should('exist')
.get('input[name="firstname"]')
.should('be.visible') // always good to check before action
.type( 'Smith')

How to combine aurelia-materialize-bridge and sweetalert2

I want to put a form in a popup.
I've found a solution but I'm looking for something cleaner.
I didn't find a way to poping-up an existing tag with swal.
So I created an hidden form in my template :
<div id="myHiddenForm"><form role="form">
<md-input class="email" md-type="email" md-label="Email" md-validate="true"
md-validate-error="invalid email">
<i md-prefix class="material-icons">account_circle</i>
</md-input>
<button type="submit" md-button>
<i class="left material-icons">done</i>Submit
</button>
</form></div>
Then I created the popup with it's innerHTML.
swal({
html: document.getElementById('myHiddenForm').innerHTML,
showConfirmButton: false,
}).catch(swal.noop);
Then I can attach a callback to the submit button and this works finally.
Obviously, I can't use md-value.bind because the displayed form is a copy of the original.
I can access the input's value, using document.querySelectorAll('#myHiddenForm .email input')[0].value but I'm wondering if there's a better way to do this ?
Maybe there's a nice approach to combine aurelia-materialize-bridge and sweetalert2.
I know there's a modal component but it's not capable of keeping the focus inside the modal popup ; plus I already use swal2 everywhere else in this webapp because, you know, it is so sweet.
After a lot of tests and the full reading of the sweetalert2 documentation, I found the correct way to handle this. We simply need to move the <form> node.
swal({
html: '<span></span>'
, showCloseButton: true
, showConfirmButton: false
, onBeforeOpen: dom => swal.getContent()
.appendChild(document.querySelectorAll('#myHiddenForm form'))
, onClose: dom => document.getElementById('myHiddenForm')
.appendChild(swal.getContent().querySelectorAll('form'))
}).catch(swal.noop);
It's perfect to use with aurelia because it preserve everything (monitors, events, validation...).
We don't even need to manually bind the submit button like I did, We can use aurelia's usual way.
Conclusion: RTFM !

Xpath not working as expected while running the test

I am trying to automate the browser, while I try to locate the element via xpath in browser in static mode it is able to highlight the element where as when I run the script it comes back with an error that it is unable to find the element.
xpath I have written:
driver.findElement(By.xpath("//input[#value='soa_b_pbtv_l0_trnkni']/following-sibling::td[1]/child::select[#name='jobaction']")));
Here is the HTML:
<form name="f2" onsubmit="return verify();" action="/ATS/cgi-bin/barcap_jobaction.pl" method="post">
<>
<input name="jobname" type="hidden" value="soa_b_pbtv_l0_trnkni"/>
<input name="jobinstance" type="hidden" value="D03"/>
<input name="jobproceed" type="hidden" value="web"/>
<td style="background-color: #ffffff;">
<select name="jobaction">
if you're trying to select the select, jobaction then try this:
use css selector for the select select[name='jobaction']
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("form[name='f2']")));
List<WebElement> eleList = driver.findElements(By.cssSelector("form[name='f2']")));
for(WebElement element: eleList) {
if(element.findElement(By.cssSelector("input[name='jobname']")).getText().equalsIgnoringCase("expectedValue")) {
WebElement element = element.findElement(By.cssSelector("select[name='jobaction']"));
}
}
The INPUT is hidden so it won't be found using typical Selenium means. Selenium was designed to only interact with elements that a user can see and interact with. You are able to locate it in the browser because you are using JS or JQuery and they are not designed to ignore hidden elements. One way to get around this is to use JavascriptExecutor... it basically allows you to run JS in Selenium and find hidden elements. Since it sounds like you already have successful locators, I would suggest you look up some tutorials on JSE and you should be set.
If you run into a new issue while using JSE, come back and post a new question and we can try to help you.

angular-file-upload - how to make drop zone clickable?

Using nv-file-upload (https://github.com/nervgh/angular-file-upload) how can I make the drop zone act also as a clickable element to select files? Adding {{nv-file-select}} does not seem to work.
The answer is that YOU CANT, there is no way to do this inside that plugin but i use a simple solution for this kind of problems. Add a ng-click inside your dragNdrop tag and call your function:
<div nv-file-drop="" uploader="upload" ng-click="launchFilePicker()">
<div class="drop-box" ng-show="upload.isHTML5" uploader="upload" nv-file-over="" over-class="dragover" filter="image/*,application/pdf">
Drag a file here.
</div>
</div>
<div ng-hide="upload.isHTML5"> <input id="fileDialog" type="file" nv-file-select uploader="upload"/><br/></div>
And inside your controller you do this:
$scope.launchFilePicker = function () {
//$('#fileDialog').click(); //not angular way
angular.element('#fileDialog').trigger('click'); //angular way
};
I hope this help.

JavaScript .innerHTMLworking only when called manually

I've got a very simple function, of replacing the innerHTML of a element. I've been trying to debug this for hours but simply can't, and it's infuriating.
When called from a button press the JavaScript (as follows) works well, but when called from another function it doesn't work. I am totally lost as to why this might be, and its a fairly core part of my app
// This loaded function in my actual code is a document listener
// checking for when Cordova is loaded which then calls the loaded function
loaded();
function loaded() {
alert("loaded");
changeText();
}
function changeText() {
alert("started");
document.getElementById('boldStuff').innerHTML = 'Fred Flinstone';
}
Button press and HTML to replace
<div id="main">
<input type='button' onclick='changeText()' value='Change Text'/>
<p>Change this text >> <b id='boldStuff'> THIS TEXT</b> </p>
</div>
It is also here in full on JSFiddle
You are already changed the innerHTML by calling the function loaded(); on onLoad.
Put this in an empty file and same as .html and open with browser and try. I have commented the function loaded();. Now it will be changed in onclick.
<div id="main">
<input type='button' onclick='changeText();' value='Change Text'/>
<p>Change this text >> <b id='boldStuff'> THIS TEXT</b> </p>
</div>
<script>
//loaded();
function loaded() {
alert("loaded");
changeText();
}
function changeText() {
alert("started");
document.getElementById('boldStuff').innerHTML = 'Fred Flinstone';
}
</script>
The problem here is, that the element you're trying to manipulate is not yet existing when you are calling the changeText() function.
To ensure that the code is only executed after the page has finished loading (and all elements are in place) you can use the onload handler on the body element like this:
<body onload="loaded();">
Additionally you should know, that it's very bad practice to manipulate values by using the innerHTML property. The correct way is to use DOM Manipulations, maybe this can help you.
You script loads before the element (boldStuff) is loaded,
Test Link - 1 - Put the js in a seperate file
Test Link - 2 - put the js at the very end, before closing the <body>