Launch Selenium using protractor or grunt - selenium-webdriver

Can someone please let me know how to integrate selenium server to start automatically without starting it in a seperate window manually using start command. I want to the test to first start the server and then run automatically
This is my conf file.
var HtmlReporter = require('protractor-html-screenshot-reporter');
var path = require('path');
// A reference configuration file.
exports.config = {
// ----- How to setup Selenium -----
//
// There are three ways to specify how to use Selenium. Specify one of the
// following:
//webdriver-manager start --standalone
// 1. seleniumServerJar - to start Selenium Standalone locally.
// 2. seleniumAddress - to connect to a Selenium server which is already
// running.
// 3. sauceUser/sauceKey - to use remote Selenium servers via SauceLabs.
seleniumAddress: 'http://localhost:4444/wd/hub',
// The location of the selenium standalone server .jar file.
seleniumServerJar: 'node_modules/protractor/selenium/selenium-server-standalone-2.40.0.jar',
// The port to start the selenium server on, or null if the server should
// find its own unused port.
seleniumPort: null,
// Chromedriver location is used to help the selenium standalone server
// find chromedriver. This will be passed to the selenium jar as
// the system property webdriver.chrome.driver. If null, selenium will
// attempt to find chromedriver using PATH.
chromeDriver: 'node_modules/grunt-protractor-runner/node_modules/protractor/node_modules/selenium-webdriver/',
// Additional command line options to pass to selenium. For example,
// if you need to change the browser timeout, use
// seleniumArgs: ['-browserTimeout=60'],
seleniumArgs: [],
// If sauceUser and sauceKey are specified, seleniumServerJar will be ignored.
// The tests will be run remotely using SauceLabs.
sauceUser: null,
sauceKey: null,
// ----- What tests to run -----
//
// Spec patterns are relative to the location of this config.
specs: [
'src/test/webapp/uitest/index.js'
],
// ----- Capabilities to be passed to the webdriver instance ----
//
// For a full list of available capabilities, see
// https://code.google.com/p/selenium/wiki/DesiredCapabilities
// and
// https://code.google.com/p/selenium/source/browse/javascript/webdriver/capabilities.js
capabilities: {
'browserName': 'chrome'
},
// A base URL for your application under test. Calls to protractor.get()
// with relative paths will be prepended with this.
baseUrl: 'http://localhost:8081',
// Selector for the element housing the angular app - this defaults to
// body, but is necessary if ng-app is on a descendant of <body>
rootElement: 'body',
onPrepare: function() {
global.isAngularSite = function(flag) {
browser.ignoreSynchronization = !flag;
};
// Add a reporter and store screenshots to `screnshots`:
jasmine.getEnv().addReporter(new HtmlReporter({
baseDirectory: 'screenshots',
pathBuilder: function pathBuilder(spec, descriptions, results, capabilities) {
var monthMap = {
"1": "Jan",
"2": "Feb",
"3": "Mar",
"4": "Apr",
"5": "May",
"6": "Jun",
"7": "Jul",
"8": "Aug",
"9": "Sep",
"10": "Oct",
"11": "Nov",
"12": "Dec"
};
var currentDate = new Date(),
currentHoursIn24Hour = currentDate.getHours(),
currentTimeInHours = currentHoursIn24Hour>12? currentHoursIn24Hour-12: currentHoursIn24Hour,
totalDateString = currentDate.getDate()+'-'+ monthMap[currentDate.getMonth()]+ '-'+(currentDate.getYear()+1900) +
'-'+ currentTimeInHours+'h-' + currentDate.getMinutes()+'m';
return path.join(totalDateString,capabilities.caps_.browserName, descriptions.join('-'));
}
}));
},
// ----- Options to be passed to minijasminenode -----
jasmineNodeOpts: {
// onComplete will be called just before the driver quits.
onComplete: null,
// If true, display spec names.
isVerbose: false,
// If true, print colors to the terminal.
showColors: true,
// If true, include stack traces in failures.
includeStackTrace: true,
// Default time to wait in ms before a test fails.
defaultTimeoutInterval: 60000
},
};
I am getting this error
[INFO] Running "protractor_webdriver:start" (protractor_webdriver) task
[INFO] Starting Selenium server
[INFO] Warning: Selenium Standalone is not present. Install with
webdriver-manager update --standalone
[INFO] Use --force to continue.
[INFO]
[INFO] Aborted due to warnings.

We use Gulp for this, this is how it looks like -
'use strict';
var global = {
app_files: {
specs: './specs/**/*.js'
},
folders: {
specs: './specs'
}
};
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');
var beautify = require('gulp-jsbeautifier');
var protractor = require('gulp-protractor').protractor;
// Download and update the selenium driver
var webdriver_update = require('gulp-protractor').webdriver_update;
var webdriver_standalone = require('gulp-protractor').webdriver_standalone;
// Downloads the selenium webdriver
gulp.task('webdriver_update', webdriver_update);
// Runs the selenium webdriver
gulp.task('webdriver_standalone', webdriver_standalone);
// Lint spec files
gulp.task('lint', function() {
return gulp.src(global.app_files.specs).pipe(jshint()).pipe(jshint.reporter(stylish)).pipe(jshint.reporter('fail'));
});
// Beautify spec files
gulp.task('beautify', function() {
return gulp.src(global.app_files.specs).pipe(beautify({
config: '.jsbeautifyrc'
})).pipe(gulp.dest(global.folders.specs));
});
gulp.task('e2e:local', ['lint', 'webdriver_update'], function() {
gulp.src([global.app_files.specs], {
read: false
}).pipe(protractor({
configFile: 'protractor.conf.js'
})).on('error', function(e) {
throw e;
});
});
gulp.task('e2e', ['e2e:local']);
and in protractor you run with - gulpe2e:local and make sure path for specs file are correct.
This should work. You should install gulp first though !

use either seleniumAddress or seleniumServerJar
I think I read somewhere that if you use seleniumAddress it will ignore seleniumServerJar and seleniumPort

Related

Websockets, truffle, ganache and react setup issues connection not open on send()

Sometimes I refresh, and it works. Sometimes it just doesn't work.
I tried changing ganache GUI settings to use port 8545 which I read is the WebSockets port but it still won't connect. ws:127.0.0.1 won't work and neither will http://
This is my truffle config file. The rest of the code is large and won't help much.
// See <http://truffleframework.com/docs/advanced/configuration>
// #truffle/hdwallet-provider
// var HDWalletProvider = require("truffle-hdwallet-provider");
const path = require("path");
var HDWalletProvider = require("#truffle/hdwallet-provider");
module.exports = {
// See <http://truffleframework.com/docs/advanced/configuration>
// to customize your Truffle configuration!
// contracts_directory: "./allMyStuff/someStuff/theContractFolder",
contracts_build_directory: path.join(__dirname, "/_truffle/build/contracts"),
// migrations_directory: "./allMyStuff/someStuff/theMigrationsFolder",
networks: {
ganache: {
host: "127.0.0.1",
port: 7545,
//port: 8545,
network_id: 5777,
//network_id: "*", // Match any network id,
websockets: false, // websockets true breaks TODO: connection not open on send()
// wss
},
},
};
This is some of my code on the actual screen in question.
const options = {
web3: {
block: false,
fallback: {
type: 'ws',
//url: 'ws://127.0.0.1:8546',
url: 'http://127.0.0.1:7545',
},
},
contracts: [MyStringStore],
// polls: {
// accounts: IntervalInMilliseconds,
// },
events: {},
};
I don't understand why sometimes it works and I can see drizzle state and sometimes I can't. React native and web3 is very new to me.
I get errors like this:
00:06 Contract MyStringStore not found on network ID: undefined
Error fetching accounts:
00:06 connection not open
I am having real difficulty setting up drizzle as well. One thing I see is that your
url: 'http://127.0.0.1:7545',
For some reason Drizzle only works with 'ws' as the prefix for such a URL. I am trying to follow this guide by people who got it working.
I think websocket is only available in the command line version.
Try install and use ganache-cli instead of the gui version.

Google Analytics optimization with r.js

Hi everyone I am trying to make r.js work but i got error on Google Analytics like this
Tracing dependencies for: main
Cannot optimize network URL, skipping: //www.google-analytics.com/analytics.js
this is my requierjs.config file
window.GoogleAnalyticsObject = "__ga__";
window.__ga__ = function() {
for (var i=0; i<arguments.length; i++) {
var arg = arguments[i];
if (arg.constructor == Object && arg.hitCallback) {
arg.hitCallback();
}
}
};
window.__ga__.q = [["create", "UA-82626142-1", "auto"]];
window.__ga__.l = Date.now();
paths: {
ga: "//www.google-analytics.com/analytics"
},
shim: {
"ga": {
exports: "__ga__"
},
}
and this is my r.js config file
{
baseUrl: "../js",
name: "main",
out: 'app-built.js',
findNestedDependencies: true,
paths: {
ga: "//www.google-analytics.com/analytics",
},
include: 'requireLib',
mainConfigFile: "../js/main.js",
}
I have used ''empty path for r.js config but i dosn`t work. Thanks in advance
I have checked Requierjs documantation again and again and i found the right way to make cdns(urls) optimize with r.js. Need write in optimize config file
paths: {
....
ga:'empty'
}
we can write 'empty' for any cdn link just need use console command when we run optimize config file like this (this is my own example from my app)
'node build/r.js -o build/build.single.js paths.ga=empty:'
Hope this will be usfulle for others who have same probleme

Simple gulp task to deploy to google app engine and stream output to console?

Is there a good way to execute the gcloud commands to deploy an app to GAE and see the stderr/stdout echoed back at the console? I've tried gulp-exec but it seems to batch up the output, dumping only upon completion. It also won't play nicely when trying to preview locally.
In the end I didn't want to have to use another npm, but loosely inspired by a portion of gulp-run, I came up with the following that assumes a 'clean' and 'build' task exists, and also overrides some constants per environment for a gulp-replace task that is part of my 'build', the key being the spawn of a subshell and piping its output to the current process's:
// gulp deploy [-a dev|staging|prod]
gulp.task('deploy', function() {
var commands = {
remote: 'gcloud preview app deploy app.yaml -q --set-default --project ',
local: 'gcloud preview app run app.yaml'
};
var environments = {
dev: {
app: 'myapp-dev',
},
staging: {
app: 'myapp-staging',
MY_ENDPOINT: 'https://staging.example.com'
},
prod: {
app: 'myapp',
MY_ENDPOINT: 'https://example.com'
}
};
var command = commands.local;
var env = environments[argv.a];
if (env) {
command = commands.remote + env.app;
constantsMap.MY_ENDPOINT = env.MY_ENDPOINT;
}
// Now that our constants are configured, kick off the build, then deploy.
runSequence('clean', 'build', function() {
var title = util.format('$ %s\n', $.util.colors.blue(command));
process.stdout.write(title);
// run the command in its own subshell and pipe the output to our own.
var subshell = childProcess.spawn('sh', ['-c', command]);
subshell.stdout.pipe(process.stdout);
subshell.stderr.pipe(process.stderr);
});
});
This relies on the npms: run-sequence, util, yargs, gulp-load-plugins
If you want to execute commands following code snippet will help you. I have wrapped it inside a promise as you are using gulp:
var cp = require('child_process');
function executeCommand(command, option) {
return new Promise(function (resolve, reject) {
var args = [option.something, option.something];
var ls = cp.spawn(command, args);
var output = "";
ls.on('error', function (err) {
reject(err);
});
ls.stdout.on('data', function (data) {
output += String(data);
console.log(output)
});
ls.on('exit', function (code) {
if (code === 0) {
resolve({
"output": output
});
} else {
reject(Error(output));
}
});
});
}
I am using gulp-gae and it seems it works well.
Supported commands are appcfg.py and dev_appserver.py (in current version). It can be also configured to override some values from the given app.yaml.

automation test using protractor with browserstack does't work with mobile browsers

I tried to set up test using angular protractor. It works fine when I use browsers of desktops, But failed with mobile browsers.
Here is the set of protractor.
seleniumAddress: 'http://hub.browserstack.com/wd/hub',
capabilities: {
'browserstack.user' : 'user',
'browserstack.key' : 'key',
'browserstack.debug': 'true',
'browserstack.local' : 'true',
'platform' : 'MAC',
'device' : 'iPad mini Retina'
},
And I got the error like this in the log of browserstack when using iphone:
<Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
<RequestId>6A1E5288B65A8A2C</RequestId>
<HostId>
ixGtp6t7yQWYa7cjkNqmaXLEHTXeKklSkf+Jmg9vnA/a+RYUfzUhJuNykqKAwOuoA3o1eQA9M9c=
</HostId>
</Error>
Error like this when using andriod
01:23 0 Injecting JavaScript-argsbodyscriptreturn (function () { var el = document.querySelector(arguments[0]); var callback = arguments[1]; try { angular.element(el).injector().get('$browser'). notifyWhenNoOutstandingRequests(callback); } catch (e) { callback(e); } }).apply(null, arguments);⇒
**This is feature will be implemented soon!**
Any one can give me some ideas about this?
You need to supply username and API key in request URL.
In your code:
http://hub.browserstack.com/wd/hub
It should be:
http://[username]:[api_key]#hub.browserstack.com/wd/hub
without [] brackets.
Also, you can read browserstack document for further understanding. https://www.browserstack.com/automate/ruby

using sauce and protractor to test internet explorer and safari

I have the following tests, which run fine when I run them locally and on sauce (at least most of the time) using firefox and chrome.
ptor = protractor.getInstance();
baseUrl = protractor.getInstance().params.sBaseUrl;
aRequiredTextFieldsKeys = [
'sFirstName',
'sLastName',
'sStreet',
'sZip',
'sCity'
];
describe('form', function ()
{
var sFormUrl = baseUrl + '#/form';
beforeEach(function ()
{
ptor.get(sFormUrl);
});
describe('wholeForm', function ()
{
it('fully filled form => required fields have correct class && submit leads to other route', function ()
{
function checkRequiredClass(el)
{
expect(el.getAttribute('class')).toContain('ng-valid-required');
}
// requried text-fields
for (var i = 0; i < aRequiredTextFieldsKeys.length; i++) {
var el = element(by.model('oFormData.' + aRequiredTextFieldsKeys[i]));
el.sendKeys('a');
checkRequiredClass(el);
}
// email
var elEmail = element(by.model('oFormData.sEmail'));
elEmail.sendKeys('jo#jo.de');
checkRequiredClass(el);
// birthday
var elBirthday = element(by.model('oFormData.oBirthday'));
elBirthday.sendKeys('1.1.1995');
checkRequiredClass(el);
// checkboxes
var elCheck1 = element(by.model('oFormData.bAgb'));
elCheck1.click();
checkRequiredClass(elCheck1);
var elCheck2 = element(by.model('oFormData.bPrivatePolicy'));
elCheck2.click();
checkRequiredClass(elCheck2);
// hack upload bon
ptor.executeScript(function ()
{
var scope = $('#application-form-id').scope();
scope.oFormData.bBonUploaded = true;
});
// submit form
element(by.className('btn-submit')).click();
ptor.getCurrentUrl()
.then(function (url)
{
expect(url).toNotBe(sFormUrl);
});
});
});
But when I launch internet explorer or safari, I get all sorts of errors, while the page works fine when tested manually. For IE I get:
Message:
UnknownError: JavaScript error (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 97
milliseconds Build info: version: '2.30.0', revision: 'dc1ef9c', time:
'2013-02-19 00:15:27' System info: os.name: 'Windows Server 2008 R2',
os.arch: 'x86', os.version: '6.1', java.version: '1.6.0_35' Session
ID: 42b30348-8598-4edb-923e-a7019ced6eb0 Driver info:
org.openqa.selenium.ie.InternetExplorerDriver Capabilities
[{platform=WINDOWS, elementScrollBehavior=0, javascriptEnabled=true,
enablePersistentHover=true, ignoreZoomSetting=false,
browserName=internet explorer, enableElementCacheCleanup=true,
unexpectedAlertBehaviour=dismiss, version=10,
cssSelectorsEnabled=true, ignoreProtectedModeSettings=false,
requireWindowFocus=false, allowAsynchronousJavaScript=false,
handlesAlerts=true, initialBrowserUrl=, nativeEvents=true,
takesScreenshot=true}]
Error: Error while waiting for Protractor to sync with the page: {"stack":"TypeError:
Unable to get property 'get' of undefined or null reference\n at Anonymous function (Unknown
script code:25:5)\n at Anonymous function (Unknown script code:21:14)\n at Anonymous
function (Unknown script code:21:2)","description":"Unable to get property 'get' of undefined
or null reference","number":-2146823281}
And for Safari:
UnknownError: Detected a page unload event; script execution does not work across page loads. (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 384 milliseconds
Build info: version: '2.33.0', revision: '4e90c97', time: '2013-05-22 15:32:38'
System info: os.name: 'Windows Server 2008 R2', os.arch: 'x86', os.version: '6.1', java.version: '1.6.0_35'
Session ID: null
Driver info: org.openqa.selenium.safari.SafariDriver
Capabilities [{platform=WINDOWS, javascriptEnabled=true, cssSelectorsEnabled=true, secureSsl=true, browserName=safari, takesScreenshot=true, version=5.1.7}]
I'm confsued about the reasons. I tried simpler tests with the same results, I tried local and remote urls and I tried all sorts of delays like waitForAngular, wait and ptor ignoreAsynch = true. None of them lead to the desired outcome. Any suggestions?
My protractor config file:
// A reference configuration file.
exports.config = {
seleniumServerJar: null,
seleniumPort: null,
chromeOnly: false,
// Additional command line options to pass to selenium. For example,
// if you need to change the browser timeout, use
// seleniumArgs: ['-browserTimeout=60'],
seleniumArgs: [],
sauceUser: 'saucesuer',
sauceKey: 'key',
allScriptsTimeout: 120000,
specs: [
'test/e2e/**/*.js',
],
// https://code.google.com/p/selenium/wiki/DesiredCapabilities
// https://code.google.com/p/selenium/source/browse/javascript/webdriver/capabilities.js
capabilities: {
'browserName': 'phantomjs',
'phantomjs.binary.path':'node_modules/phantomjs/bin/phantomjs'
},
// Selector for the element housing the angular app - this defaults to
// body, but is necessary if ng-app is on a descendant of <body>
rootElement: 'body',
onPrepare: function ()
{
// driver.manage().timeouts().setScriptTimeout(60000);
},
params: {
sBaseUrl: 'https://dev.com/'
},
baseUrl: 'http://localhost:8000',
framework: 'jasmine',
// ----- Options to be passed to minijasminenode -----
//
// See the full list at https://github.com/juliemr/minijasminenode
jasmineNodeOpts: {
// onComplete will be called just before the driver quits.
onComplete: null,
// If true, display spec names.
isVerbose: true,
// If true, print colors to the terminal.
showColors: true,
// If true, include stack traces in failures.
includeStackTrace: true,
// Default time to wait in ms before a test fails.
defaultTimeoutInterval: 120000
}
};
WHile it doesnt seem to matter, I use grunt-protractor runner to run multiple instances sequentially.
chrome: {
options: {
args: {
browser: 'chrome',
"idle-timeout": 120
}
}
},
firefox: {
options: {
args: {
browser: 'firefox'
}
}
},
ie9: {
options: {
args: {
browser: 'internet explorer',
version: '9',
"idle-timeout": 120
}
}
},
ie10: {
options: {
args: {
browser: 'internet explorer',
version: '10'
}
}
},
safari7: {
options: {
args: {
browser: 'safari',
version: '7'
}
}
},
safari6: {
options: {
args: {
browser: 'safari',
version: '6'
}
}
},
safari5: {
options: {
args: {
browser: 'safari',
version: '5'
}
}
}
}
grunt.registerTask('e2eall', [
'protractor:ie9',
'protractor:ie10',
'protractor:safari5',
'protractor:safari6',
'protractor:safari7',
'protractor:firefox',
'protractor:chrome'
]);
Hugo,
This is an issue with certain test configurations that was partially solved in Protractor 0.17 and more definitively solved in 0.18. I would recommend updating your protractor to latest (0.18.1 at the time of this post) and seeing if that solves your issue.
Relevant changelog entries:
v0.18
(10aec0f) fix(pageload): increase wait timeout
The 300 ms wait caused problems when testing IE on Sauce Labs. It seems way too short. "browser.get()" invariably timed out. Increasing it solved our problem.
v0.17
(a0bd84b) fix(pageload): add a wait during protractor.get() to solve unload issues
Some systems would not wait for the browser unload event to finish before beginning the asynchronous script execution.
Closes #406. Closes #85.
Hope that helps!

Resources