using sauce and protractor to test internet explorer and safari - angularjs

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!

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.

webpack-dev-server set cookie via proxy

We have setup our development environment with webpack-dev-server. We use its proxy config to communicate with the backend.
We have a common login page in the server which we use in all our applications. We it is called, it sets a session cookie which expected to passed with subsequent requests. We have used the following config but the cookie is not set in the browser for some reason. I can see it in response header in the network tab of dev tool.
const config = {
devServer: {
index: "/",
proxy: {
"/rest_end_point/page": {
target: "https://middleware_server",
secure : false
},
"/": {
target: "https://middleware_server/app/login",
secure : false
},
}
The https://middleware_server/app/login endpoint returns the login page with the set-cookie header.
The proxy is used to avoid CORS errors when accessing login pages and API calls.
Upto this point no code from the application is executed. Do we have to do something in the coomon login page to get the cookie set?
the application is written with React.
Any help would be appreciated.
I have the same use case and this is what I have done.
In my case, I have multiple proxy targets so I have configured the JSON (ProxySession.json) accordingly.
Note: This approach is not dynamic. you need to get JSESSIONID manually(session ID) for the proxy the request.
login into an application where you want your application to proxy.
Get the JSESSIONID and add it in JSON file or replace directly in onProxyReq function and then run your dev server.
Example:
Webpack-dev.js
// Webpack-dev.js
const ProxySession = require("./ProxySession");
config = {
output: {..........},
plugins: [.......],
resolve: {......},
module: {
rules: [......]
},
devServer: {
port: 8088,
host: "0.0.0.0",
disableHostCheck: true,
proxy: {
"/service/**": {
target: ProxySession.proxyTarget,
changeOrigin: true,
onProxyReq: function(proxyReq) {
proxyReq.setHeader("Cookie", "JSESSIONID=" + ProxySession[buildType].JSESSIONID + ";msa=" + ProxySession[buildType].msa + ";msa_rmc=" + ProxySession[buildType].msa_rmc + ";msa_rmc_disabled=" + ProxySession[buildType].msa_rmc);
}
},
"/j_spring_security_check": {
target: ProxySession.proxyTarget,
changeOrigin: true
},
"/app_service/websock/**": {
target: ProxySession.proxyTarget,
changeOrigin: true,
onProxyReq: function(proxyReq) {
proxyReq.setHeader("Cookie", "JSESSIONID=" + ProxySession[buildType].JSESSIONID + ";msa=" + ProxySession[buildType].msa + ";msa_rmc=" + ProxySession[buildType].msa_rmc + ";msa_rmc_disabled=" + ProxySession[buildType].msa_rmc);
}
}
}
}
ProxySession.json
//ProxySession.json
{
"proxyTarget": "https://t.novare.me/",
"build-type-1": {
"JSESSIONID": "....",
"msa": "....",
"msa_rmc": ...."
},
"build-type-2": {
"JSESSIONID": ".....",
"msa": ".....",
"msa_rmc":"....."
}
}
I met the exact same issue, and fixed it by this way:
This is verified and worked, but it's not dynamic.
proxy: {
'/my-bff': {
target: 'https://my.domain.com/my-bff',
changeOrigin: true,
pathRewrite: { '^/my-bff': '' },
withCredentials: true,
headers: { Cookie: 'myToken=jx42NAQSFRwXJjyQLoax_sw7h1SdYGXog-gZL9bjFU7' },
},
},
To make it dynamic way, you should proxy to the login target, and append a onProxyRes to relay the cookies, something like: (not verified yet)
onProxyRes: (proxyRes: any, req: any, res: any) => {
Object.keys(proxyRes.headers).forEach(key => {
res.append(key, proxyRes.headers[key]);
});
},
"/api/**": {
...
cookieDomainRewrite: { "someDomain.com": "localhost" },
withCredentials: true,
...
}
You can use this plugin to securely manage auth cookies for webpack-dev-server:
A typical workflow would be:
Configure a proxy to the production service
Login on the production site, copy authenticated cookies to the local dev server
The plugin automatically saves your cookie to system keychain
https://github.com/chimurai/http-proxy-middleware#http-proxy-options
use option.cookieDomainRewrite and option.cookiePathRewrite now
cookies ??
devServer: {
https: true, < ------------ on cookies
host: "127.0.0.1",
port: 9090,
proxy: {
"/s": {
target: "https://xx < --- https
secure: false,
//pathRewrite: { "^/s": "/s" },
changeOrigin: true,
withCredentials: true
}
}
}
. . . . . . . . . . .

How to catch AngularJS Error with Protractor

I'm experiencing some problem while E2E testing an AngularJS app with Protractor. To sum things up: I have the following specification and the first step always fails with a btstrpd error. (The page is auto-bootstrapped and we use AngularJS v1.3.0 and Protractor v2.1.0.)
describe('Protractor Demo App', function() {
it('should have a title', function() {
browser.get('http://myapp.abc.de/ext/#/login');
expect(browser.getTitle()).toEqual('My App');
});
it('should do other stuff', function() {
// ...
});
});
Error:
1) Protractor Demo App should have a title
Message:
UnknownError: unknown error: [ng:btstrpd] http://errors.angularjs.org/1.3.15/ng/btstrpd?p0=document
(Session info: chrome=43.0.2357.132)
(Driver info: chromedriver=2.15.322448 (52179c1b310fec1797c81ea9a20326839860b7d3),platform=Windows NT 6.1 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 9 milliseconds
(Full description here)
Since I don't seem to find a solution to prevent this error and the remaining test steps run without any problems, my approach would be to simply ignore the error. However I don't want the test case to fail due to it. This brings me to my question: How can I catch this error so that the test won't fail? A plain try-catch around the two statements in the step does not the trick and since I don't have any promises here I also cannot do the typical promise error handling as one would manually handle e.g. a NoSuchElementError.
Edit - Error in webdriver console:
12:06:18.975 INFO - Executing: [new session: Capabilities [{count=1, browserName
=chrome}]])
12:06:18.995 INFO - Creating a new session for Capabilities [{count=1, browserNa
me=chrome}]
Starting ChromeDriver 2.15.322448 (52179c1b310fec1797c81ea9a20326839860b7d3) on
port 23267
Only local connections are allowed.
12:06:21.248 INFO - Done: [new session: Capabilities [{count=1, browserName=chro
me}]]
12:06:21.271 INFO - Executing: [set script timeoutt: 11000])
12:06:21.281 INFO - Done: [set script timeoutt: 11000]
12:06:21.390 INFO - Executing: [get: data:text/html,<html></html>])
12:06:21.405 INFO - Done: [get: data:text/html,<html></html>]
12:06:21.425 INFO - Executing: [execute script: window.name = "NG_DEFER_BOOTSTRA
P!" + window.name;window.location.replace("http://myapp.abc.de/ext/#/login");, [
]])
12:06:23.440 INFO - Done: [execute script: window.name = "NG_DEFER_BOOTSTRAP!" +
window.name;window.location.replace("http://myapp.abc.de/ext/#/login");, []]
12:06:23.458 INFO - Executing: [execute script: return window.location.href;, []
])
12:06:23.468 INFO - Done: [execute script: return window.location.href;, []]
12:06:23.489 INFO - Executing: [execute async script: try { return (function (at
tempts, asyncCallback) {
var callback = function(args) {
setTimeout(function() {
asyncCallback(args);
}, 0);
};
var check = function(n) {
try {
if (window.angular && window.angular.resumeBootstrap) {
callback([true, null]);
} else if (n < 1) {
if (window.angular) {
callback([false, 'angular never provided resumeBootstrap']);
} else {
callback([false, 'retries looking for angular exceeded']);
}
} else {
window.setTimeout(function() {check(n - 1);}, 1000);
}
} catch (e) {
callback([false, e]);
}
};
check(attempts);
}).apply(this, arguments); }
catch(e) { throw (e instanceof Error) ? e : new Error(e); }, [10]])
12:06:25.603 INFO - Done: [execute async script: try { return (function (attempt
s, asyncCallback) {
var callback = function(args) {
setTimeout(function() {
asyncCallback(args);
}, 0);
};
var check = function(n) {
try {
if (window.angular && window.angular.resumeBootstrap) {
callback([true, null]);
} else if (n < 1) {
if (window.angular) {
callback([false, 'angular never provided resumeBootstrap']);
} else {
callback([false, 'retries looking for angular exceeded']);
}
} else {
window.setTimeout(function() {check(n - 1);}, 1000);
}
} catch (e) {
callback([false, e]);
}
};
check(attempts);
}).apply(this, arguments); }
catch(e) { throw (e instanceof Error) ? e : new Error(e); }, [10]]
12:06:25.633 INFO - Executing: [execute script: return (function () {
angular.module('protractorBaseModule_', []).
config(['$compileProvider', function($compileProvider) {
if ($compileProvider.debugInfoEnabled) {
$compileProvider.debugInfoEnabled(true);
}
}]);
}).apply(null, arguments);, []])
12:06:25.643 INFO - Done: [execute script: return (function () {
angular.module('protractorBaseModule_', []).
config(['$compileProvider', function($compileProvider) {
if ($compileProvider.debugInfoEnabled) {
$compileProvider.debugInfoEnabled(true);
}
}]);
}).apply(null, arguments);, []]
12:06:25.663 INFO - Executing: [execute script: angular.resumeBootstrap(argument
s[0]);, [[protractorBaseModule_]]])
12:06:26.093 WARN - Exception thrown
org.openqa.selenium.WebDriverException: unknown error: [ng:btstrpd] http://error
s.angularjs.org/1.3.15/ng/btstrpd?p0=document
(Session info: chrome=43.0.2357.134)
(Driver info: chromedriver=2.15.322448 (52179c1b310fec1797c81ea9a20326839860b7
d3),platform=Windows NT 6.1 SP1 x86_64) (WARNING: The server did not provide any
stacktrace information)
Command duration or timeout: 10 milliseconds
Build info: version: '2.45.0', revision: '5017cb8', time: '2015-02-26 23:59:50'
System info: host: 'xxxxx', ip: 'xxx.xxx.xx.x', os.name: 'Windows 7', os.arch: '
amd64', os.version: '6.1', java.version: '1.8.0_45'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEn
abled=false, chrome={userDataDir=C:\Users\abcdefg\AppData\Local\Temp\scoped_dir1
1436_18156}, takesHeapSnapshot=true, databaseEnabled=false, handlesAlerts=true,
version=43.0.2357.134, platform=XP, browserConnectionEnabled=false, nativeEvents
=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true,
browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsE
nabled=true}]
Session ID: 0c39849d960cccef7ec7036b8414c9fb
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Sou
rce)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.
java:204)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHa
ndler.java:156)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.ja
va:599)
at org.openqa.selenium.remote.RemoteWebDriver.executeScript(RemoteWebDri
ver.java:508)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.openqa.selenium.support.events.EventFiringWebDriver$2.invoke(Even
tFiringWebDriver.java:101)
at com.sun.proxy.$Proxy1.executeScript(Unknown Source)
at org.openqa.selenium.support.events.EventFiringWebDriver.executeScript
(EventFiringWebDriver.java:213)
at org.openqa.selenium.remote.server.handler.ExecuteScript.call(ExecuteS
cript.java:53)
at java.util.concurrent.FutureTask.run(Unknown Source)
at org.openqa.selenium.remote.server.DefaultSession$1.run(DefaultSession
.java:168)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
12:06:26.103 WARN - Exception: unknown error: [ng:btstrpd] http://errors.angular
js.org/1.3.15/ng/btstrpd?p0=document
(Session info: chrome=43.0.2357.134)
(Driver info: chromedriver=2.15.322448 (52179c1b310fec1797c81ea9a20326839860b7
d3),platform=Windows NT 6.1 SP1 x86_64) (WARNING: The server did not provide any
stacktrace information)
Command duration or timeout: 10 milliseconds
Build info: version: '2.45.0', revision: '5017cb8', time: '2015-02-26 23:59:50'
System info: host: 'xxxx', ip: 'xxx.xxx.xx.x', os.name: 'Windows 7', os.arch: '
amd64', os.version: '6.1', java.version: '1.8.0_45'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEn
abled=false, chrome={userDataDir=C:\Users\abcdefg\AppData\Local\Temp\scoped_dir1
1436_18156}, takesHeapSnapshot=true, databaseEnabled=false, handlesAlerts=true,
version=43.0.2357.134, platform=XP, browserConnectionEnabled=false, nativeEvents
=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true,
browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsE
nabled=true}]
Session ID: 0c39849d960cccef7ec7036b8414c9fb
12:06:26.203 INFO - Executing: [delete session: f947352d-3b40-4b1b-a46a-9d4ffe32
8b76])
12:06:27.417 INFO - Done: [delete session: f947352d-3b40-4b1b-a46a-9d4ffe328b76]
In your code, I would put a WaitforAngular() to make sure the sync append with Angular & Protractor. See bellow for reference:
it('should have a title', function() {
browser.get('http://myapp.abc.de/ext/#/login');
browser.waitForAngular();
expect(browser.getTitle()).toEqual('My App');
});
Then if it does not work, I would use the browser.pause(); command. This will break the execution of protractor where you use the command. From there you can open the Chrome debuging console to see what is appening exactly.
You can also use the REPL debuging mode it is very convenient way to check that you element are present on the page and that you are using the correct selector.
Please refer to the following link for more informations on debugging with protractor: https://angular.github.io/protractor/#/debugging

Launch Selenium using protractor or grunt

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

Issues with Protractor and Element Explorer resolving elements on page

I am able to run my protractor tests against localhost, but when hitting my in-house test server, I can't get protractor to find elements on the page. The same issues occur with Protractor 1.3.1 and 1.4.0 with the latest Chrome and Firefox drivers.
...AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\atoms\error.js:113
var template = new Error(this.message);
^
Process finished with exit code 1
So I've been trying to use the Element explorer to debug the issue, but it is giving me the following:
> list(by.css('#logindropdown'))
There was a webdriver error: UnknownError unknown error: Runtime.evaluate threw exception: TypeError: Cannot read property 'click' of null
(Session info: chrome=38.0.2125.111)
(Driver info: chromedriver=2.12.301325 (962dea43ddd90e7e4224a03fa3c36a421281abb7),platform=Windows NT 6.1 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 28 milliseconds
Build info: version: '2.44.0', revision: '76d78cf', time: '2014-10-23 20:02:37'
System info: host: 'NB2D1469', ip: '158.147.71.49', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_67'
Session ID: 85966371ff89f75af8cf7fb5d15f6f23
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{platform=XP, acceptSslCerts=true, javascriptEnabled=true, browserName=chrome, chrome={userDataDir=C:\Users\mprent99\AppData\Local\Temp\scoped_dir6488_12276}, rotatable=false, locationContextEnabled=true, mobileEmulationEnabled=false, version=38.0
.2125.111, takesHeapSnapshot=true, cssSelectorsEnabled=true, databaseEnabled=false, handlesAlerts=true, browserConnectionEnabled=false, webStorageEnabled=true, nativeEvents=true, applicationCacheEnabled=false, takesScreenshot=true}]
Simple things like list(by.css('body')) also give the same exception above. Using by.id give the same results, list(by.id('logindropdown'))
Commands that have no results (when they should) seem to avoid the exceptions:
> list(by.css('a .caret'))
[ '' ]
> list(by.css('.caret'))
[ '' ]
In the webdriver-manager terminal, I am seeing the following:
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:599)
at org.openqa.selenium.remote.RemoteWebDriver.executeAsyncScript(RemoteWebDriver.java:526)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.openqa.selenium.support.events.EventFiringWebDriver$2.invoke(EventFiringWebDriver.java:101)
at com.sun.proxy.$Proxy1.executeAsyncScript(Unknown Source)
at org.openqa.selenium.support.events.EventFiringWebDriver.executeAsyncScript(EventFiringWebDriver.java:225)
at org.openqa.selenium.remote.server.handler.ExecuteAsyncScript.call(ExecuteAsyncScript.java:55)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at org.openqa.selenium.remote.server.DefaultSession$1.run(DefaultSession.java:168)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
and
17:05:00.256 INFO - Executing: [execute async script: try { return (function (rootSelector, callback) {
var el = document.querySelector(rootSelector);
try {
if (angular.getTestability) {
angular.getTestability(el).whenStable(callback);
} else {
angular.element(el).injector().get('$browser').
notifyWhenNoOutstandingRequests(callback);
}
} catch (e) {
callback(e);
}
}).apply(this, arguments); }
catch(e) { throw (e instanceof Error) ? e : new Error(e); }, [body]])
17:05:00.562 WARN - Exception thrown
org.openqa.selenium.WebDriverException: unknown error: Runtime.evaluate threw exception: TypeError: Cannot read property 'click' of null
Versions in use:
protractor --version
Version 1.4.0 or Version 1.3.1
node --version
v0.10.30
webdriver-manager status
selenium standalone is up to date
chromedriver is up to date
IEDriver is not present
These same things work just fine in Chrome DevTools:
('.caret')
[<b class=​"caret">​</b>​]
$('a .caret')
[<b class=​"caret">​</b>​]
$('#logindropdown')
[<li id=​"logindropdown" class=​"dropdown ng-scope">​…​</li>​]
$('body')
[<body class=​"vertical-grow">​…​</body>​]
Here is the onPrepare where the failure appears to be happening:
onPrepare: function() {
var username = element(by.model('login.userName'));
var password = element(by.model('login.password'));
browser.driver.get(env.baseUrl);
browser.driver.findElement(by.css('a .caret')).click();
username.sendKeys('user#company.com');
password.sendKeys('password');
browser.driver.findElement(by.css('.btn-primary')).click();
// Login takes some time, so wait until it's done.
// For the test app's login, we know it's done when it redirects to index.html.
browser.driver.wait(function() {
return browser.driver.getCurrentUrl().then(function(url) {
return (/dashboards/).test(url);
});
}, 5000);
}
Here is the rest of the conf.js:
/*global browser,element,by */
var env = require('./env.js');
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: [
'loginTest.js'
],
suites: {
//smoke: 'spec/smoketests/*.js',
//full: 'spec/*.js'
},
directConnect: false,
multiCapabilities: [
// {browserName: 'firefox'}
{browserName: 'chrome'}
],
maxSessions: -1,
framework: 'jasmine',
// Options to be passed to Jasmine-node.
jasmineNodeOpts: {
// 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: 360000
},
// 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: 'html'
};
How do I debug this farther and get to the root of this issue?

Resources