Protractor upload stuck when filesearch pops up - protractor

I'm trying to figure out what's wrong with the code below:
it('should upload a photo', function(){
var photo = './photos/et-test.jpeg',
exactPhoto = path.resolve(__dirname, photo);
var form = element(by.id('fileupload'));
var upload = element(by.css('input[type = "file"]'));
var addFiles = element(by.cssContainingText('.btn.btn-success.fileinput-button.mb-10','Add files...'));
var uploadBtn = element(by.css('.btn.btn-primary.start.mt-20'));
element(by.cssContainingText('.inline_link','Upload more album photos now')).click();
element(by.id('secondary_upload_link')).click();
browser.wait(EC.visibilityOf(addFiles), 5000);
addFiles.click();
upload.sendKeys(exactPhoto);
browser.wait(EC.visibilityOf(uploadBtn), 5000);
uploadBtn.click();
expect(element(by.css('.table')).getText()).toBe('Upload Finised');
});
I keep getting stuck on the filesearch popup and receive this error:
Message:
Failed: Wait timed out after 5006ms
Is there anything lacking or should've been done based on the flow of my code?

If I'm understanding your issue correctly you are seeing a popup window when uploading a file. Can you try the following capability in your conf (assuming you are using Chrome)
capabilities: {
browserName: 'chrome',
chromeOptions: {
prefs: {
download: {
'prompt_for_download': false,
'directory_upgrade': true,
'default_directory': 'src/test/javascript/e2e/downloads'(or where ever you prefer)
}
}
}
}

Yes, you don't need to click on it, just sendKeys() for this input element
Sometimes it needs to make this input visible. Just try like that (it works in my case for await/async protractor):
private addAttachment = element(by.css('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; arguments[0].style.display = 'inline'; arguments[0].style.overflow = 'visible'", this.addAttachment)
await browser.executeScript("arguments[0].focus();", await this.addAttachment.getWebElement())
await this.addAttachment.sendKeys(path)

Try this:
var photo = './photos/et-test.jpg',
exactPhoto = path.resolve(__dirname, photo);
var form = element(by.id('fileupload')); ///Users/leochardc/ET/photos/et-test.jpg
var upload = element(by.css('.fileupload_section input[type = "file"]'));
var addFiles = element(by.cssContainingText('.btn.btn-success.fileinput-button.mb-10','Add files...'));
var uploadBtn = element(by.css('.btn.btn-primary.start.mt-20'));
var uploadFinished = element(by.css('.fileupload_section .text-center p'));
browser.get(url);
element(by.cssContainingText('.inline_link','Upload more album photos now')).click();
element(by.id('secondary_upload_link')).click();
browser.wait(EC.visibilityOf(addFiles), 5000);
// addFiles.click();
upload.sendKeys(exactPhoto);
var previewPic = element(by.css('.fileupload_section.fileupload_files'));
browser.wait(EC.visibilityOf(previewPic), 5000);
browser.wait(EC.visibilityOf(uploadBtn), 5000);
uploadBtn.click();
browser.wait(EC.visibilityOf(uploadFinished), 30000);
expect(uploadFinished.getText()).toBe('Upload Finished');

Related

Protractor : Wait for element doesn't work in the 'second browser instance' of a same test

I am trying to use multiple browsers in the same test, script fails when i try to wait for the element present in second browser.
var browser2 = browser.forkNewDriverInstance(true);
browser2.get('https://test.app.com');
var EC = protractor.ExpectedConditions;
browser2.wait(EC.visibilityOf($('.meeting-btn>span')),15000); //Script fails here
browser2.$('.meeting-btn>span').click();
console.log("clicked Meeting button");
*Error:
Failed: Wait timed out after 15010ms
The element is actually present in the screen but wait keyword isn't locating the element. The script actually works when i write the code in following manner.
var browser2 = browser.forkNewDriverInstance(true);
browser2.get('https://test.app.com');
var EC = protractor.ExpectedConditions;
browser.sleep(15000);
browser2.$('.meeting-btn>span').click();
console.log("clicked Meeting button");
Script fails only when i insert wait keyword. Any suggestions would be helpful.
Your error is this line:
browser2.wait(EC.visibilityOf($('.meeting-btn>span')),15000); //Script fails here
Using $('.meeting-btn>span') implicitly uses the main browser so is equivalent to browser.$('.meeting-btn>span'), which can't be found in browser2.
To fix the error, use:
browser2.wait(EC.visibilityOf(browser2.$('.meeting-btn>span')),15000); //Script fixes
To avoid this kind of error during developpment, I usually define my ElementFinder first, then re-use it. See "targetElement" here:
var browser2 = browser.forkNewDriverInstance(true);
browser2.get('https://test.app.com');
const targetElement = browser2.$('.meeting-btn>span');
var EC = protractor.ExpectedConditions;
browser2.wait(EC.visibilityOf(targetElement),15000); //Script fails here
targetElement.click();
console.log("clicked Meeting button");
To test this code in a new project:
follow setup steps from https://www.protractortest.org/#/
change conf.js so it looks like the following:
exports.config = {
// seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['todo-spec.js'],
directConnect: true,
// SELENIUM_PROMISE_MANAGER: true
};
create test file test.js:
function checkElements(targetBrowser) {
const targetURL = 'https://angular.io/';
targetBrowser.get(targetURL);
const targetSelector = 'a.button.hero-cta.no-print';
const targetElem = targetBrowser.$(targetSelector);
var EC = protractor.ExpectedConditions;
targetBrowser.wait(EC.visibilityOf(targetElem),15000); //Script fails here
targetElem.click();
// title is present
const titleElem = targetBrowser.$("#getting-started-with-angular");
expect(titleElem.getText()).toEqual('Getting started with Angular');
}
describe('angular homepage', function() {
it('test with browser', function() {
checkElements(browser);
});
it('test with 2nd browser', function() {
const browser2 = browser.forkNewDriverInstance(true);
checkElements(browser2);
});
});
add another it method with the code from this answer:
it('MY TEST', function() {
var browser2 = browser.forkNewDriverInstance(true);
browser2.get('https://test.app.com');
const targetElement = browser2.$('.meeting-btn>span');
var EC = protractor.ExpectedConditions;
browser2.wait(EC.visibilityOf(targetElement),15000); //Script fails here
targetElement.click();
console.log("clicked Meeting button");
});
run protractor: "protractor conf.js"

sapui5 how to read PDF file content in controller

Im facing an issue in PDF File Uploading..
In the above Screenshot if you see, When im trying to upload a PDF file, Im not able to read the content in that pdf file.
My requirement is like, I need to get the content as String from that file and that content i need to send to back-end server..
Im getting below error if im trying to read the content
HTTP Status 405 - Bad Method
Below is my Code ..
Im using xmlns:u="sap.ui.unified" library
<u:FileUploader id="fileUploader" name="myFileUpload" tooltip="Upload Service Sheet"
uploadComplete="handleUploadComplete" change="handleValueChange" typeMissmatch="handleTypeMissmatch" style="Emphasized" fileType="pdf"
placeholder="Choose a file for Upload..." maximumFileSize="2000" mimeType="pdf" buttonText="Upload">
</u:FileUploader>
handleUploadComplete: function(oEvent) {
var fileName = oEvent.getSource().getProperty("value");
var sResponse = oEvent.getParameter("response");
if (sResponse) {
var sMsg = "";
var m = /^\[(\d\d\d)\]:(.*)$/.exec(sResponse);
if (m[0] == "200") {
sMsg = "Return Code: " + m[0] + "(Upload Success)";
oEvent.getSource().setValue("");
} else {
sMsg = "Return Code: " + m[0] + "(Upload Error)";
}
MessageToast.show(sMsg);
}
},
Can some one please help me how can i read the data in the PDF??
Thank you in advance
Take a look at this example. Hope this helps.
View
<u:FileUploader change="onChange" fileType="pdf" mimeType="pdf" buttonText="Upload" />
Controller
convertBinaryToHex: function(buffer) {
return Array.prototype.map.call(new Uint8Array(buffer), function(x) {
return ("00" + x.toString(16)).slice(-2);
}).join("");
},
onChange: function(oEvent){
var that = this;
var reader = new FileReader();
var file = oEvent.getParameter("files")[0];
reader.onload = function(e) {
var raw = e.target.result;
var hexString = that.convertBinaryToHex(raw).toUpperCase();
// DO YOUR THING HERE
};
reader.onerror = function() {
sap.m.MessageToast.show("Error occured when uploading file");
};
reader.readAsArrayBuffer(file);
},

Store image to Firebase storage from cordova camera plugins on Ionic

I've red some topics on the subject (e.g: Uploading image to Firebase Storage from Cordova app) but didn't find my answer...
I'm working on a IONIC project with the implementation of the ngCordova camera plugin to take picture and get pic from the librairy.
So I got the result as a image URI and I want to upload it in Firebase storage (as file or Blob).
Here is my code :
$scope.fromCamera = function() {
$ionicPlatform.ready(function() {
var options = {
quality: 75,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 300,
targetHeight: 300,
saveToPhotoAlbum: true e
};
$cordovaCamera.getPicture(options).then(function(imageURI) {
window.resolveLocalFileSystemURL(imageURI, function (fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function () {
// This blob object can be saved to firebase
var blob = new Blob([new Uint8Array(this.result)], { type: "image/jpeg" });
// Create the storage ref
var ref = storageRef.child('images/test');
// Upload the file
uploadPhoto(blob, ref);
};
reader.readAsArrayBuffer(file);
});
}, function (error) {
console.log(error)
});
});
});
};
I read the file and convert it into a Blob before uploading it into firebase. And I got an 'Encoding error' telling me "A URI supplied to the API was malformed, or the resulting Data URL has exceeded the URL length limitations for Data URLs."
I'm running it an chrome browser with the Cordova Mocks extension.
Any help is welcome!
Thanks
uploadPhoto() is my function to upload the file on firebase storage (and save the URL in firebase database)
var storageRef = Firebase.storageRef();
var databaseRef = Firebase.databaseRef();
var uploadPhoto = function(file, ref) {
var task = ref.put(file);
// Update progress bar
task.on('state_changed', function(snapshot){
// nothing
}, function(error) {
// Handle unsuccessful uploads
}, function() {
// Handle successful uploads on complete
$scope.downloadURL = task.snapshot.downloadURL;
$scope.actualKey = databaseRef.child('posts').push().key;
databaseRef.child('posts/' + $scope.actualKey).update({
url : $scope.downloadURL,
id : $scope.actualKey,
time : firebase.database.ServerValue.TIMESTAMP,
});
}
);
}
try changing...
[new Uint8Array(this.result)]
to just this
[this.result]
alternate approach using $cordovaFile
var fileName = imageURI.replace(/^.*[\\\/]/, '');
$cordovaFile.readAsArrayBuffer(cordova.file.tempDirectory, fileName)
.then(function (success) {
// success - get blob data
var imageBlob = new Blob([success], { type: "image/jpeg" });
// Create the storage ref
var ref = storageRef.child('images/test');
// Upload the file
uploadPhoto(imageBlob, ref);
}, function (error) {
// error
});
Instead of getting the path from the URI, in the code, I assume the following...
// modify the image path when on Android
if ($ionicPlatform.is("android")) {
path = cordova.file.cacheDirectory
} else {
path = cordova.file.tempDirectory
}
feel free to parse the path to get the directory

Cannot read property 'download' of undefined $cordovaFileTransfer in Ionic

I want to use $cordovaFileTransfer in my app to dowload image data, but after trying to implement the code, this error is showing up:
Cannot read property 'download' of undefined
here is my code:
var url = "blablabla.com/img.png";
var targetPath = "img/"+ imgpaths;
var trustHosts = true;
var options = {};
$cordovaFileTransfer.download(url, targetPath, options, trustHosts)
.then(function(result) {
// Success!
console.log('Download Success' + targetPath);
}, function(err) {
// Error
}, function (progress) {
$timeout(function () {
var downloadProgress = (progress.loaded / progress.total) * 100;
console.log('Progress : '+downloadProgress);
});
});
anybody can help me?
Check this issues list:
http://ngcordova.com/docs/common-issues/
For example have you wrapped the call to $cordovaFileTransfer.download() inside deviceready handler or better inside $ionicPlatform.ready() ?

Titanium: can't switch tabs, close tabs, anything other than my current tab

Everything I try just does nothing, no errors, message, really anything. So I have three tabs, the first being a login tab, each tab has its own .js code, so for example, the login has its own login.js. Now, I use the httpClient to authenticate back to our website, and now want to remove the login tab and display the other tabs, cannot get it to work for the life of me, I can now remove the login tab but cannot load ay of the other tabs. Driving me nuts because I am finding 20 examples but they either don't separate the tabs into their own .js files or the example just plain doesn't work for me. Help! This seems so basic but yet...
app.js
// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Titanium.UI.setBackgroundColor('#000');
// create tab group
var tabGroup = Titanium.UI.createTabGroup();
// create base UI tab and root window
//
var scan = Titanium.UI.createWindow({
title:'Scan',
backgroundColor:'#fff',
url:'scan.js',
mylabel:'Hello Scan'
});
var tab1 = Titanium.UI.createTab({
icon:'KS_nav_views.png',
title:'Scan',
window:scan
});
var login = Titanium.UI.createWindow({
title:'User Authentication',
tabBarHidden:true,
url:'login.js'
});
var loginTab = Titanium.UI.createTab({
title:"Login",
window:login
});
//
// create controls tab and root window
//
var win2 = Titanium.UI.createWindow({
title:'Manual',
backgroundColor:'#fff'
});
var tab2 = Titanium.UI.createTab({
icon:'KS_nav_ui.png',
title:'Manual',
window:win2
});
var label2 = Titanium.UI.createLabel({
color:'#999',
text:'I am Manual Window ',
font:{fontSize:20,fontFamily:'Helvetica Neue'},
textAlign:'center',
width:'auto'
});
win2.add(label2);
//
// add tabs
//
tabGroup.addTab(loginTab);
tabGroup.addTab(tab1);
tabGroup.addTab(tab2);
// open tab group
tabGroup.open();
login.js
var win = Titanium.UI.currentWindow;
var tabGroup = Ti.UI.currentWindow.tabGroup;
var appUrl = "http://localhost:3001/ticket_agents/sign_in";
var email = Titanium.UI.createTextField({
color:'#336699',
top:10,
left:10,
width:300,
height:40,
hintText:'Email',
keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
returnKeyType:Titanium.UI.RETURNKEY_DEFAULT,
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
});
win.add(email);
var password = Titanium.UI.createTextField({
color:'#336699',
top:60,
left:10,
width:300,
height:40,
hintText:'Password',
passwordMask:true,
keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
returnKeyType:Titanium.UI.RETURNKEY_DEFAULT,
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
});
win.add(password);
var loginBtn = Titanium.UI.createButton({
title:'Login',
top:110,
width:90,
height:35,
borderRadius:1,
font:{fontFamily:'Arial',fontWeight:'bold',fontSize:14}
});
var loginReq = Titanium.Network.createHTTPClient({
onload : function(e) {
var json = this.responseText;
var response = JSON.parse(json);
Ti.API.info("Received text: " + this.responseText);
if (response.id > 0)
{
alert("login Success");
win.tabGroup.close();
tabGroup.removeTab(loginTab);
tabGroup.setActiveTab(2);
tabGroup.open();
}
else
{
alert("Unknown login error");
}
},
onerror : function(e) {
var response = this.responseText;
Ti.API.debug(e.error);
alert('error: ' + this.responseText);
},
timeout : 5000
});
loginBtn.addEventListener('click',function(e)
{
if (email.value != '' && password.value != '')
{
loginReq.open("POST",appUrl);
var params = {ticket_agent: {email: email.value, password: password.value, remember_me: 0}
};
var authstr = 'Basic ' + Titanium.Utils.base64encode(email.value + ':' + password.value);
loginReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
loginReq.setRequestHeader('Authorization', authstr);
loginReq.send(JSON.stringify(params));
}
else
{
alert("Email/Password are required");
}
});
win.add(loginBtn);
I think that's all you'd need to see, the login.js has my latest attempt but I've tried things like tabGroup.open({url : 'app.js'}) and about three our four other option. Thanks.
You may want to add this eventListener to your app.js where the tabGroup is.
You can then fire a "app:gotoTab" event from anywhere.
app.js
Ti.App.addEventListener('app:gotoTab', function(e) {
tabGroup.setActiveTab(e.tab);
});
login.js
// tab index starts with 0, so 0 is your first tab
Ti.App.fireEvent('app:gotoTab', { tab: 0 });
Simply Copy paste this code
Login.js
var win = Titanium.UI.currentWindow;
var appUrl = "http://localhost:3001/ticket_agents/sign_in";
var email = Titanium.UI.createTextField({
color:'#336699',
top:10,
left:10,
width:300,
height:40,
hintText:'Email',
keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
returnKeyType:Titanium.UI.RETURNKEY_DEFAULT,
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
});
win.add(email);
var password = Titanium.UI.createTextField({
color:'#336699',
top:60,
left:10,
width:300,
height:40,
hintText:'Password',
passwordMask:true,
keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
returnKeyType:Titanium.UI.RETURNKEY_DEFAULT,
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
});
win.add(password);
var loginBtn = Titanium.UI.createButton({
title:'Login',
top:110,
width:90,
height:35,
borderRadius:1,
font:{fontFamily:'Arial',fontWeight:'bold',fontSize:14}
});
var loginReq = Titanium.Network.createHTTPClient({
onload : function(e) {
var json = this.responseText;
var response = JSON.parse(json);
Ti.API.info("Received text: " + this.responseText);
if (response.id > 0)
{
alert("login Success");
tabGroup.setActiveTab(2);
}
else
{
alert("Unknown login error");
}
},
onerror : function(e) {
var response = this.responseText;
Ti.API.debug(e.error);
alert('error: ' + this.responseText);
},
timeout : 5000
});
loginBtn.addEventListener('click',function(e)
{
if (email.value != '' && password.value != '')
{
loginReq.open("POST",appUrl);
var params = {ticket_agent: {email: email.value, password: password.value, remember_me: 0}
};
var authstr = 'Basic ' + Titanium.Utils.base64encode(email.value + ':' + password.value);
loginReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
loginReq.setRequestHeader('Authorization', authstr);
loginReq.send(JSON.stringify(params));
}
else
{
alert("Email/Password are required");
}
});
win.add(loginBtn);
Hey Ross, You always remember window.close work on child Window perfectly.
In this application. You can use single Window base Application.
If, In First Window Login Successfully then, you can OPEN Second child Window.
for more details you can use KICHEN Shink Example. this is very useful for You.
You may want to redesign your UI. The Apple Human Interface Guidelines specifically say that you shouldn't programmatically switch tabs or add/remove tabs. They expect that a tabgroup should only be controlled by the user once you put it in front of them.
If the user needs to log in before they can use other features of your app you can present the a login window before the window with the tab group. Otherwise, you should replace the content of the login tab with something else after a successful login, perhaps with user profile information or some instructions.