Download file to given absolute path in Firefox using Protractor - firefox

Im using Protractor for E2E testing. During automation, I need to download files to C:\Automation folder in my system. But below code is not working.
Note:During automation execution,The Save as popup opens(but i have to disable that in future) and I manually click "Save" option. It saves in default location ie Downloads folder.How do I make it save in my given path.
let profile = require('firefox-profile');
let firefoxProfile = new profile();
//_browser = 'chrome';
_browser = 'firefox';
// _browser = 'internet explorer';
firefoxProfile.setPreference("browser.download.folderList", 2);
firefoxProfile.setPreference('browser.download.dir', "C:\\Automation");
exports.config = {
framework: 'custom',
frameworkPath: require.resolve('protractor-cucumber-framework'),
capabilities: {
'browserName': _browser,
'shardTestFiles': false,
'maxInstances': 1,
'acceptInsecureCerts': true,
'moz:firefoxOptions': {
'profile': firefoxProfile
}},
beforeLaunch: function () {...}
}

It looks like you may just be missing a couple of preferences for it to work with firefox. Try adding these and see if that helps.
profile.setPreference( "browser.download.manager.showWhenStarting", false );
profile.setPreference( "browser.helperApps.neverAsk.saveToDisk",
/* A comma-separated list of MIME types to save to disk without asking goes here */ );

this will save to downloads folder inside your project. You can try to tweak it to save to desired folder. You have to specify which types of files are suppose to be downloaded without prompt. JSON and csv are already there.
var q = require('q');
var path = require('path');
var sh = require("shelljs");
var cwd = sh.pwd().toString();
var FirefoxProfile = require('selenium-webdriver/firefox').Profile;
var makeFirefoxProfile = function(preferenceMap) {
var profile = new FirefoxProfile();
for (var key in preferenceMap) {
profile.setPreference(key, preferenceMap[key]);
}
return q.resolve({
browserName: 'firefox',
marionette: true,
firefox_profile: profile
});
};
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
framework: 'jasmine2',
getMultiCapabilities: function() {
return q.all([
makeFirefoxProfile(
{
'browser.download.folderList': 2,
'browser.download.dir': (path.join(cwd, 'downloads')).toString(),
'browser.download.manager.showWhenStarting': false,
'browser.helperApps.alwaysAsk.force': false,
'browser.download.manager.useWindow': false,
'browser.helperApps.neverAsk.saveToDisk': 'application/octet-stream, application/json, text/comma-separated-values, text/csv, application/csv, application/excel, application/vnd.ms-excel, application/vnd.msexcel, text/anytext, text/plaintext'
}
)
]);
},
allScriptsTimeout: 1000000,
specs: ['./tmp/**/*.spec.js'],
jasmineNodeOpts: {
defaultTimeoutInterval: 1000000,
showColors: true
},
onPrepare: function() {
browser.driver.getCapabilities().then(function(caps) {
browser.browserName = caps.get('browserName');
});
setTimeout(function() {
browser.driver.executeScript(function() {
return {
width: window.screen.availWidth,
height: window.screen.availHeight
};
}).then(function(result) {
browser.driver.manage().window().setPosition(0,0);
browser.driver.manage().window().setSize(result.width, result.height);
});
});
}
};

Related

How use MediaFilePicker and PhotoEditor plugins in Nativescript

I am trying to use MediaFilePicker on nativescript and at the same time use the PhotoEditor plugin to crop/edit the photo taken from the camera but I don't make it work... here is part of my code:
let options: ImagePickerOptions = {
android: {
isCaptureMood: true, // if true then camera will open directly.
isNeedCamera: true,
maxNumberFiles: 1,
isNeedFolderList: true
}, ios: {
isCaptureMood: true, // if true then camera will open directly.
maxNumberFiles: 1
}
};
let mediafilepicker = new Mediafilepicker();
mediafilepicker.openImagePicker(options);
mediafilepicker.on("getFiles", function (res) {
let results = res.object.get('results');
let result = results[0];
let source = new imageSourceModule.ImageSource();
source.fromAsset(result.rawData).then((source) => {
const photoEditor = new PhotoEditor();
photoEditor.editPhoto({
imageSource: source,
hiddenControls: [],
}).then((newImage) => {
}).catch((e) => {
reject();
});
});
});
The result object of the FilePicker comes like:
{
"type": "capturedImage",
"file": {},
"rawData": "[Circular]"
}
I believe if the picture was taken from the camera, then use the rawData field, but I dont know which format is coming and how to give it to PhotoEditor pluging to play with it.
Any suggestions?
Thanks!
The issue was at this line source.fromAsset(result.rawData) here, result.rawData is not an ImageAsset but it's PHAsset. You will have to create an ImageAsset from PHAsset and pass it on to fromAsset. So it would look like,
import { ImageAsset } from "tns-core-modules/image-asset";
....
....
imgSource.fromAsset(new ImageAsset(img)).then((source) => {
const photoEditor = new PhotoEditor();
console.log(source === imgSource);
photoEditor.editPhoto({
imageSource: source,
hiddenControls: [],
}).then((newImage: ImageSource) => {
console.log('Get files...');
// Here you can save newImage, send it to your backend or simply display it in your app
}).catch((e) => {
//reject();
});
});

How to upload image with FILE_URI distination to firebase storage in Ionic 2

I'm trying to upload captured image to firebase storage after edit it by some custom editor.
My problem under two cases:
Case1 : If I used this code, then I can upload the image but I can't use my custom editor
takePicture(){
let options: CameraOptions;
options = {
quality : 85,
destinationType: this.camera.DestinationType.DATA_URL,
sourceType : this.camera.PictureSourceType.CAMERA,
allowEdit : false,
encodingType: this.camera.EncodingType.JPEG,
correctOrientation: true,
saveToPhotoAlbum: true
}
this.camera.getPicture(options).then((imageData) => {
this.currentOriginalImageUri = 'data:image/jpeg;base64,' + imageData;
this.currentDocumentImageUri = 'data:image/jpeg;base64,' + imageData;
});
}
Case2 : If I used this code, then I can use the function of custom editor but I can't upload my image
takePicture(){
let options: CameraOptions;
options = {
quality : 85,
destinationType: this.camera.DestinationType.FILE_URI,
sourceType : this.camera.PictureSourceType.CAMERA,
allowEdit : false,
encodingType: this.camera.EncodingType.JPEG,
correctOrientation: true,
saveToPhotoAlbum: true
}
this.camera.getPicture(options).then((imageData) => {
this.currentOriginalImageUri = imageData;
this.currentDocumentImageUri = imageData;
});
}
Note: This is my uploading function
private uploadPhoto(): void {
let loader = this.loadingCtrl.create({
content: ""
})
loader.present().then(_=>{
return this.myPhotosRef.child(this.generateUUID()).child('myPhoto.JPEG').putString(this.currentDocumentImageUri,firebase.storage.StringFormat.DATA_URL).then((savedPicture) => {
this.currentDocumentImageUri = savedPicture.downloadURL;
this.afd.list('/notesImages/').push({
note_id: this.appService.id,
url: this.currentDocumentImageUri,
date: new Date().toISOString()
});
});
}).then(_=>{
loader.dismiss();
this.viewCtrl.dismiss();
})
}
So is there any way to use the both cases?
You are saving image as a string in the database. If you want to upload a file using file path using the linked api (assuming data_url is not working for your custom editor)
Try put() instead of putString().
return this.myPhotosRef.child(this.generateUUID()).child('myPhoto.JPEG').put(this.currentDocumentImageUri).then((savedPicture) => {
// rest of code
});

Protractor beforeAll() not running

I was trying to run a test that had worked the day before and got an error message saying
- Error: Error while waiting for Protractor to sync with the page: "window.angular is undefined. This could be either because this is a non-angular page or because your test involves client-side navigation, which can interfere with Protractor's bootstrapping. See http://git.io/v4gXM for details"
I added a console.log("hi") in one of my beforeAll() calls and there was no output in the console, so I suspect the error is that beforeAll() is not invoked for some reason.
I'm using the latest jasmine framework in my conf file and some of my tests run when I don't include the beforeAll(), but not all of them. This test was working fine yesterday and I ran it again today without any changes, so I'm not sure what the problem might be. Does anyone else know?
I'll include my conf.js file and part of the test I'm running.
My conf.js file
let SpecReporter = require('jasmine-spec-reporter').SpecReporter;
exports.config = {
framework: 'jasmine',
directConnect: true,
allScriptsTimeout: 50000,
rootElement: 'html',
untrackOutstandingTimeouts: true,
// suites: {
//HealthCheck: './specs/Health Check/**.js',
//ContectCheck: './specs/Content Check/**.js',
// },
specs: [
// 'specs/submitFeedback.js',
'specs/createTeacherAndStudentOld.js',
// 'specs/temp.js',
// 'specs/manipTeste.js',
],
capabilities: {
browserName: 'chrome'
},
params: {
screenWidth: 1920,
screenHeight: 1080,
siteURL: 'https://alpha.khmath.com',
marketingSiteURL: 'https://knowledgehook.com',
portalUsername: '',
portalPassword: '',
classRedemptionCode: 'testcode1',
contentCheckCourse: 'Grade 9 Academic',
homeWorkCourse: 'Grade 9 Applied',
gameShowCourse: 'Grade 9 Applied',
term: '2016-2017 Full Year',
gameShowSiteUrl: 'https://alpha.khmath.com/play'
},
jasmineNodeOpts: {
defaultTimeoutInterval: 7200000,
print: function() {}
},
onPrepare: function () {
global.helper = require('./helper.js');
global.completeQuestionHelper = require('./pages/student/completeQuestionHelper.js');
global.fs = require('fs');
global.https = require('https');
global.LoginPage = require('./pages/loginPage.js');
global.RegistrationPage = require('./pages/registrationPage.js');
global.TeacherGameShowPage = require('./pages/teacher/teacherGameShowPage.js');
global.TeacherHomePage = require('./pages/teacher/teacherHomePage.js');
global.TeacherMissionPage = require('./pages/teacher/teacherMissionPage.js');
global.TeacherPurchasePage = require('./pages/teacher/teacherPurchasePage.js');
global.TeacherStudentsPage = require('./pages/teacher/teacherStudentsPage.js');
global.TeacherStudentSummaryPage = require('./pages/teacher/teacherStudentSummaryPage.js');
global.TeacherReportPage = require('./pages/teacher/teacherReportPage.js');
global.StudentHomePage = require('./pages/student/studentHomePage.js');
global.StudentAllSkillsPage = require('./pages/student/studentAllSkillsPage.js');
global.StudentSkillPage = require('./pages/student/studentSkillPage.js');
global.StudentGameplayPage = require('./pages/student/studentGameplayPage.js');
global.StudentMissionPage = require('./pages/student/studentMissionPage.js');
global.StudentPortfolioPage = require('./pages/student/StudentPortfolioPage.js');
global.GameShowStudentGameplayPage = require('./pages/gameshow/gameShowStudentGameplayPage.js');
global.GameShowStudentRegistrationPage = require('./pages/gameshow/gameShowStudentRegistrationPage.js');
global.GameShowTeacherGameplayPage = require('./pages/gameshow/gameShowTeacherGameplayPage.js');
global.loginPage = new LoginPage(browser);
global.registrationPage = new RegistrationPage(browser);
global.teacherGameShowPage = new TeacherGameShowPage(browser);
global.teacherHomePage = new TeacherHomePage(browser);
global.teacherMissionPage = new TeacherMissionPage(browser);
global.teacherPurchasePage = new TeacherPurchasePage(browser);
global.teacherStudentsPage = new TeacherStudentsPage(browser);
global.teacherStudentSummaryPage = new TeacherStudentSummaryPage(browser);
global.teacherReportPage = new TeacherReportPage(browser);
global.studentHomePage = new StudentHomePage(browser);
global.studentAllSkillsPage = new StudentAllSkillsPage(browser);
global.studentSkillPage = new StudentSkillPage(browser);
global.studentGameplayPage = new StudentGameplayPage(browser);
global.studentMissionPage = new StudentMissionPage(browser);
global.studentPortfolioPage = new StudentPortfolioPage(browser);
global.gameShowStudentGameplayPage = new GameShowStudentGameplayPage(browser);
global.gameShowStudentRegistrationPage = new GameShowStudentRegistrationPage(browser);
global.gameShowTeacherGameplayPage = new GameShowTeacherGameplayPage(browser);
global.EC = protractor.ExpectedConditions;
jasmine.getEnv().addReporter(new SpecReporter({
spec: {
displayStacktrace: true
},
colors: {
enabled: false,
},
prefixes: {
successful: "O ",
failed: "X ",
},
}));
},
};
My spec file
beforeAll(function () {
console.log('hi');
helper.setBrowserParams(browser);
browser.get(browser.params.siteURL);
});
it('should register a teacher and create a premium class', function () {
//Click Register
loginPage.registerBtn.click();
...
`

Retrieve the current platform in SauceLabs

I'm trying to write my custom Jasmine reporter for my Protractor tests running on SauceLabs.
I can easily get the current browser using browser.getCapabilities() but how can I get the platform?
var multiCapabilities = [
{
'browserName': 'chrome',
'platform': 'Windows 7',
},
{
'browserName': 'chrome',
'platform': 'Linux',
}
];
exports.config = {
framework: 'jasmine2',
onPrepare: function () {
browser.getCapabilities().then(function (capabilities) {
var browserName = capabilities.caps_.browserName
var browserVersion = capabilities.caps_.version
// How can I get the full platform here??? i.e OS name + version
})
}
};
Thanks!
This will return the value you are looking for:
browser.getProcessedConfig().then(function (config) {
var platformName = config.capabilities.platform;
});
All of the capabilities are available with this method, so you could use browser.getProcessedConfig() for the browserName and browserVersion as well.

Jasmine HTML2 Reporter

I have been using Jasmine2-HTML-Reporter and it's been fine. Produces a multi-spec report with screenshots - just as I need.
However, something seems to have gone awry! Now I will only get a report for the first Spec and nothing for any other spec. Also, the system used to delete the previous report/screenshot but now this has to be done manually.
I really cannot think what's changed in the rest of the package to cause this!!
Here's the entry in the conf.js files...identical for each conf file. I've tried adding the various switches - no effect at all!
Thanks
var Jasmine2HtmlReporter = require('protractor-jasmine2-html-reporter');
exports.config = {
//seleniumAddress: 'http://localhost:444/wd/hub',
params: require ('Models/Baths.js'),
directConnect: true,
capabilities: {
cssSelectorsEnabled: true,
'browserName': 'chrome',
specs:['Specs/001-First.js',
'Specs/003-Exp.js'
],
allScriptsTimeout: 120000,
getPageTimetout: 30000,
framework: 'jasmine2',
showColors: true,
isVerbose: true,
onPrepare: function() {
Jasmine.getEnv().addReporter(
new Jasmine2HtmlReporter({
takeScreenshots: true,
savePath: './Reports',
fileName: 'B&Q'
})
);
var SpecReporter = require ( 'jasmine-spec-reporter').SpecReporter;
jasmine.getEnv().addReporter( new SpecReporter( {
displayStacktrace: true,
displayFailureSummary: true,
displayPendingSummary: true,
displaySuccessfulSpec: true,
displayFailedSpec: true,
displaySpecDuration: true,
displaySuiteNumber: false,
colors: {
success: 'green',
failure: 'red',
pending: 'yellow'
},
customProcessors: []
} ));
}
}
};
Try with below conf file, it should work for you.
var Jasmine2HtmlReporter = require('protractor-jasmine2-html-reporter');
var log4js = require('log4js');
var params = process.argv;
var args = process.argv.slice(3);
exports.config = {
//seleniumServerJar: './node_modules/gulp-protractor/node_modules/protractor/selenium/selenium-server-standalone-2.48.2.jar',
seleniumAddress: 'http://localhost:4444/wd/hub',
allScriptsTimeout: 100000,
framework: 'jasmine2',
onPrepare: function () {
browser.manage().timeouts().implicitlyWait(11000);
var width = 768;
var height = 1366;
browser.driver.manage().window().setSize(768, 1366);
browser.ignoreSynchronization = false;
jasmine.getEnv().addReporter(
new Jasmine2HtmlReporter({
savePath: __dirname+'/qualityreports/testresults/e2e',
takeScreenshots: false,
filePrefix: 'automationReport',
consolidate: true,
cleanDestination: false,
consolidateAll: true
})
);
},
suites:{
example:['./test/e2e/specs/**/*Spec.js',]
},
capabilities: {
'browserName': 'chrome'
},
resultJsonOutputFile:'./results.json',
// Options to be passed to Jasmine-node.
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 100000
}
};

Resources