File upload with webdriverio v5 in msedge - selenium-webdriver

I am running an automation test in sauceLabs using webdriverio v5. I want to run a test which is uploading a file to msedge. Below is the sample code for the same.
const path = require('path');
const filePath = path.join(__dirname, 'path/to/your/file');
const remoteFilePath = browser.uploadFile(filePath);
$('upload file input selector').setValue(remoteFilePath);
This code works fine with chrome and firefox but when i try to run the same in msedge is gives Error: The uploadFile command is not available in msedge.
Seems like browser.uploadFile only works for chrome. i have tried various other things but the solutions works mostly on local and not on remote server like sauceLabs.
Is there any alternative for browser.uploadFile or any workaround which can be used to upload the file in msedge browser?

Looks like for security reasons, browser.uploadFile is not available to use for IE and Edge browsers.
I suggest you try to make a test with the code sample below.
It first finds the file upload element and then it uses sendkeys() to set the path value in control.
// fetch the element
WebElement input = driver.findElement(By.XPath("//input[#type='file']"));
// send file path keys
input.sendKeys(path);
If the issue persists then you can try the below example.
// fetch the element
WebElement input = driver.findElement(By.XPath("//input[#type='file']"));
// run JS to reveal the element
JavascriptExecutor executor = (JavaScriptExecutor)driver;
executor.executeScript("arguments[0].style.display = 'block';", input);
// send file path keys
input.sendKeys(path);
Reference:
Selenium how to upload files to Microsoft Edge
Note: You may need to convert the above code into your developing language.

Related

I am using AutoJsContext in geckobrowser with that I am using evaluate scrpit. But now i am using webview2 is there a how can i get this

I am using AutoJsContext in geckobrowser with that I am using evaluate scrpit and asble to get data. But now i am using webview2 is there a how can i get this.
Gecko browser:
using (AutoJSContext context = new AutoJSContext(browser.Window))
{
var userIdResult = context
.EvaluateScript("userId", (nsIDOMWindow)browser.Window.DomWindow);
}
Above is the code I use in gecko browser. now i need to get user id from webview2. Please help me in this issue
I am not able to get any alternative
You can use CoreWebView2.ExecuteScriptAsync to inject script into the current top-level document of the WebView2 and receive the result as a JSON string. The method doesn't have a way to specify an execution context. Script is executed in the global context of the top-level document similar to running script in the console of DevTools in the browser.
For example something like the following:
var resultAsJSON = await coreWebView2.ExecuteScriptAsync('window.userId');

Way to implement resetApp for React Native with wdio-cli/? - webdriverio

Hellow there! I am using the wdio/cli so I created the wdio.conf.js with this command, then I start doing the test. But the issues is when have more than one test in a single or multiple test files.
In the test file I have something like this:
beforeEach(async function() {
$('~home').waitForDisplayed(81000, false);
});
Where home tag is a tag in the first view when the app runs in first screen. And appear this error:
element ("~home") still not displayed after 10000ms
So need to do kind of driver.resetApp()/ But dont know how to do it, what import do I need to do etc.
Did you try resetApp? You can't user driver as "main object" - Everything is under browser variable. Try this
//async
await browser.resetApp();
//sync
browser.resetApp();
Check Appium doc + wdio documentation.

Meteor FS link leads to 404 Error

I am currently developing a Meteor React app, which is using the ostrio:files package to store audio files in a collection named Files. In another (regular mongo) collection, I am using the following code in the transform function to "join" the document with the link to the audio file:
transform: function(doc){
let curAudio = doc.audio;
let audioFile = Files.collection.findOne({_id: curAudio.file_id});
if(audioFile){
curAudio.audioLink = Files.link(audioFile);
curAudio.audioLength = audioFile.meta.length;
curAudio.audioSize = audioFile.size;
doc.audio = curAudio;
}
return doc;
}
This seems to work just fine, as the resulting audio.audioLink is something like
http://localhost:3000/cdn/storage/files/8Q7WwEXyJSkNWwFQa/original/8Q7WwEXyJSkNWwFQa.m4a
But when I try to do something like this
<audio controls preload="none" style={{width: "480px"}}>
<source src={track.audioLink} type="audio/mp4"/>
<p>Your browser does not support HTML5 audio.</p>
</audio>
To be able to play the file, everything works until I click the play button of the HTML5 player. Then, chrome outputs to the console, that the server returned 404 when the file was supposed to be loaded. I tested putting the link into the adress bar, here the server response is just
File Not Found :(
Does anyone have an idea how to fix this?
I found the answer:
My local Ubuntu installation was apparently configured to store uploaded files in /tmp, which didn't caus problems until I restarted the system or cleared my temporary files otherwise. Having the server recreate the DB fixed the problem.

How to check if file got downloaded from browser using selenium2library

Can someone help me How to check if file got downloaded from browser using selenium2library,RobotFramework.In my current test I am able to click the download button and file is getting downloaded but what happens if the file didn't get downloaded eventhough button is clicked. Any sample code is helpful.
In chrome I open the chrome://downloads page and then retrieve the downloaded files list from shadow DOM like this:
const docs = document
.querySelector('downloads-manager')
.shadowRoot.querySelector('#downloads-list')
.getElementsByTagName('downloads-item');
This solution is restrained to chrome, the data also contains information like file path and download date.
Check out this link -
http://ardesco.lazerycode.com/testing/webdriver/2012/07/25/how-to-download-files-with-selenium-and-why-you-shouldnt.html
Also, here's how you can auto-download the file to a particular directory -
FirefoxProfile profile = new FirefoxProfile();
profile.SetPreference("browser.download.folderList",2);
profile.SetPreference("browser.download.dir", #"c:\path\to\downloads \folder");
FirefoxDriver driver = new FirefoxDriver(profile);
u can use following python function to download file without showing dialog box.
Also u can set preference for which type of files save file dialog box should not get displayed.
def create_profile():
from selenium import webdriver
fp =webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.dir",'C:/Users/mra001/Downloads/Cambium_Builds')
fp.set_preference("browser.helperApps.neverAsk.saveToDisk",'text/csv/xls')
fp.update_preferences()
return fp.path

How to upload file in angularjs e2e protractor testing

I want to test file uploading using an angularjs e2e test. How do you do this in e2e tests? I run my test script through grunt karma.
This is how I do it:
var path = require('path');
it('should upload a file', function() {
var fileToUpload = '../some/path/foo.txt',
absolutePath = path.resolve(__dirname, fileToUpload);
element(by.css('input[type="file"]')).sendKeys(absolutePath);
element(by.id('uploadButton')).click();
});
Use the path module to resolve the full path of the file that you want to upload.
Set the path to the input type="file" element.
Click on the upload button.
This will not work on firefox. Protractor will complain because the element is not visible. To upload in firefox you need to make the input visible. This is what I do:
browser.executeAsyncScript(function(callback) {
// You can use any other selector
document.querySelectorAll('#input-file-element')[0]
.style.display = 'inline';
callback();
});
// Now you can upload.
$('input[type="file"]').sendKeys(absolutePath);
$('#uploadButton').click();
You can't directly.
For security reason, you can not simulate a user that is choosing a file on the system within a functional testing suite like ngScenario.
With Protractor, since it is based on WebDriver, it should be possible to use this trick
Q: Does WebDriver support file uploads? A: Yes.
You can't interact with the native OS file browser dialog directly,
but we do some magic so that if you call
WebElement#sendKeys("/path/to/file") on a file upload element, it does
the right thing. Make sure you don't WebElement#click() the file
upload element, or the browser will probably hang.
This works just fine:
$('input[type="file"]').sendKeys("/file/path")
Here is a combo of Andres D and davidb583's advice that would have helped me as I worked through this...
I was trying to get protractor tests executed against the flowjs controls.
// requires an absolute path
var fileToUpload = './testPackages/' + packageName + '/' + fileName;
var absolutePath = path.resolve(__dirname, fileToUpload);
// Find the file input element
var fileElem = element(by.css('input[type="file"]'));
// Need to unhide flowjs's secret file uploader
browser.executeScript(
"arguments[0].style.visibility = 'visible'; arguments[0].style.height = '1px'; arguments[0].style.width = '1px'; arguments[0].style.opacity = 1",
fileElem.getWebElement());
// Sending the keystrokes will ultimately submit the request. No need to simulate the click
fileElem.sendKeys(absolutePath);
// Not sure how to wait for the upload and response to return first
// I need this since I have a test that looks at the results after upload
// ... there is probably a better way to do this, but I punted
browser.sleep(1000);
var imagePath = 'http://placehold.it/120x120&text=image1';
element(by.id('fileUpload')).sendKeys(imagePath);
This is working for me.
This is what I do to upload file on firefox, this script make the element visible to set the path value:
browser.executeScript("$('input[type=\"file\"]').parent().css('visibility', 'visible').css('height', 1).css('width', 1).css('overflow', 'visible')");
If above solutions don't work, read this
First of all, in order to upload the file there should be an input element that takes the path to the file. Normally, it's immediately next to the 'Upload' button... BUT I've seen this, when the button doesn't have an input around the button which may seem to be confusing. Keep clam, the input has to be on the page! Try look for input element in the DOM, that has something like 'upload', or 'file', just keep in mind it can be anywhere.
When you located it, get it's selector, and type in a path to a file. Remember, it has to be absolute path, that starts from you root directory (/something/like/this for MAC users and C:/some/file in Windows)
await $('input[type="file"]').sendKeys("/file/path")
this may not work, if...
protractor's sendKeys can only type in an input that's visible. Often, the input will be hidden or have 0 pixels size. You can fix that too
let $input = $('input[type="file"]');
await browser.executeScript(
"arguments[0].style.visibility = 'visible'; arguments[0].style.height = '1px'; arguments[0].style.width = '1px'; arguments[0].style.opacity = 1",
$input.getWebElement()
);
I realized that the file input in the web app I'm testing is only visible in Firefox when it is scrolled into view using JavaScript, so I added scrollIntoView() in Andres D's code to make it work for my app:
browser.executeAsyncScript(function (callback) {
document.querySelectorAll('input')[2]
.style = '';
document.querySelectorAll('input')[2].scrollIntoView();
callback();
});
(I also removed all of the styles for the file input element)
// To upload a file from C:\ Directory
{
var path = require('path');
var dirname = 'C:/';
var fileToUpload = '../filename.txt';
var absolutePath = path.resolve('C:\filename.txt');
var fileElem = ptor.element.all(protractor.By.css('input[type="file"]'));
fileElem.sendKeys(absolutePath);
cb();
};
If you want to select a file without opening the popup below is the answer :
var path = require('path');
var remote = require('../../node_modules/selenium-webdriver/remote');
browser.setFileDetector(new remote.FileDetector());
var fileToUpload = './resume.docx';
var absolutePath = path.resolve(process.cwd() + fileToUpload);
element(by.css('input[type="file"]')).sendKeys(absolutePath);
the current documented solutions would work only if users are loading jQuery. i all different situations users will get an error such:Failed: $ is not defined
i would suggest to document a solution using native angularjs code.
e.g. i would suggest instead of suggesting:
$('input[type="file"]') .....
to suggest:
angular.element(document.querySelector('input[type="file"]')) .....
the latter is more standard, atop of angular and more important not require jquery

Resources