karma-sauce-launcher disconnects every test run resulting in failed runs with IE and Safari - karma-runner

I have been having this exact issue for months now, through multiple versions of each component involved (karma, socket.io, sauce-connect). Currently I'm running on Karma 12.16.
Basically, when using https://github.com/karma-runner/karma-sauce-launcher, Safari and IE browsers launched disconnect every single test run resulting in only a partial test run. The relevant Karma log is
Driving the web on session: abf7c976abf1420a9c72b3e06c655040
DEBUG [wd]: > RESPONSE init({"base":"SauceLabs","browserName":"internet explorer","platform":"Windows 8.1","version":"11","tags":[],"name":"Karma and Sauce Labs demo","record-video":false,"record-screenshots":true,"build":null,"device-orientation":null,"disable-popup-handler":true}) "abf7c976abf1420a9c72b3e06c655040",null
INFO [launcher.sauce]: internet explorer 11 (Windows 8.1) session at https://saucelabs.com/tests/abf7c976abf1420a9c72b3e06c655040
DEBUG [launcher.sauce]: WebDriver channel for internet explorer 11 (Windows 8.1) instantiated, opening http://localhost:9876/?id=15483642
DEBUG [wd]: > CALL get("http://localhost:9876/?id=15483642")
DEBUG [wd]: > POST /session/:sessionID/url {"url":"http://localhost:9876/?id=15483642"}
DEBUG [web-server]: serving: /Volumes/OSXSTORAGE/Users/a/Dropbox/a/WebstormProjects/a-ui/node_modules/karma/static/client.html
DEBUG [web-server]: serving: /Volumes/OSXSTORAGE/Users/a/Dropbox/a/WebstormProjects/a-ui/node_modules/karma/static/karma.js
DEBUG [wd]: > RESPONSE get("http://localhost:9876/?id=15483642")
DEBUG [karma]: A browser has connected on socket xXySXoeppVtPhAr8FVR4
INFO [IE 11.0.0 (Windows)]: Connected on socket xXySXoeppVtPhAr8FVR4 with id 15483642
DEBUG [launcher]: internet explorer 11 (Windows 8.1) on SauceLabs (id 15483642) captured in 17.693 secs
DEBUG [web-server]: serving: /Volumes/OSXSTORAGE/Users/a/Dropbox/a/WebstormProjects/a-ui/node_modules/karma/static/context.html
DEBUG [web-server]: serving (cached): /Volumes/OSXSTORAGE/Users/a/Dropbox/a/WebstormProjects/a-ui/src/components/angular/angular.js
................................................................................
..............DEBUG [karma]: A browser has connected on socket mGf0VzQ8DKdfW_NSFVR5
DEBUG [IE 11.0.0 (Windows)]: New connection mGf0VzQ8DKdfW_NSFVR5 (already have xXySXoeppVtPhAr8FVR4)
WARN [IE 11.0.0 (Windows)]: Disconnected (1 times), because no message in 10000 ms.
IE 11.0.0 (Windows): Executed 94 of 94 DISCONNECTED (11.481 secs / 0.757 secs)
DEBUG [launcher.sauce]: Shutting down the internet explorer 11 (Windows 8.1) driver
DEBUG [wd]: > CALL get("about:blank")
DEBUG [wd]: > POST /session/:sessionID/url {"url":"about:blank"}
DEBUG [karma]: Run complete, exitting.
DEBUG [launcher]: Disconnecting all browsers
DEBUG [wd]: > RESPONSE get("about:blank")
DEBUG [wd]: > CALL quit()
DEBUG [wd]: > DELETE /session/:sessionID
DEBUG [wd]:
Ending your web drivage..
DEBUG [wd]: > RESPONSE quit()
I have tried increasing browserNoActivityTimeout to 60000, but that just results in the tests failing after 60s instead of 10s. Every one of these failed has the following:
DEBUG [karma]: A browser has connected on socket mGf0VzQ8DKdfW_NSFVR5
DEBUG [IE 11.0.0 (Windows)]: New connection mGf0VzQ8DKdfW_NSFVR5 (already have xXySXoeppVtPhAr8FVR4)
WARN [IE 11.0.0 (Windows)]: Disconnected (1 times), because no message in 10000 ms.
IE 11.0.0 (Windows): Executed 94 of 94 DISCONNECTED (11.481 secs / 0.757 secs)
Depending on the browser, sometimes it will only execute 50 tests (Executed 50 of 94 DISCONNECTED), and on others it will execute all tests, but still be considered a failed test run. I have never seen this occur with Chrome or Firefox.
The exact same karma.conf file will run every time locally with no issues. Has anyone encountered this? I have reached out to saucelabs support, but they are starting to insist that this is a karma-sauce-launcher issue.
Karma.conf:
var fs = require('fs');
module.exports = function(config) {
// Use ENV vars on Travis and sauce.json locally to get credentials
if (!process.env.SAUCE_USERNAME) {
if (!fs.existsSync('sauce.json')) {
console.log('Create a sauce.json with your credentials based on the sauce-sample.json file.');
process.exit(1);
} else {
process.env.SAUCE_USERNAME = require('./../sauce').username;
process.env.SAUCE_ACCESS_KEY = require('./../sauce').accessKey;
}
}
// Browsers to run on Sauce Labs
var customLaunchers = {
sl_safari_ml: {
base: 'SauceLabs',
browserName: 'safari',
platform: 'OS X 10.9'
}
};
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '../',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'src/components/jquery/dist/jquery.js',
'src/components/angular/angular.js',
'src/components/angular-mocks/angular-mocks.js',
'src/components/angular-cookies/angular-cookies.js',
'src/components/angular-sanitize/angular-sanitize.js',
'src/components/angular-ui-router/release/angular-ui-router.js',
'src/components/angular-animate/angular-animate.js',
'src/components/angular-strap/dist/angular-strap.js',
'src/components/angular-strap/dist/angular-strap.tpl.js',
'src/components/speakingurl/lib/index.js',
'src/app/**/*.js',
'src/app/common/templates/*.html'
],
exclude: [
'src/app/**/*.e2e.spec.js'
],
ngHtml2JsPreprocessor: {
stripPrefix: 'src/app/common/',
moduleName: 'mywire.templates'
},
preprocessors: {
// load templates
'src/app/common/templates/*.html': ['ng-html2js']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['dots'],
// web server port
port: 9876,
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
sauceLabs: {
testName: 'Karma and Sauce Labs demo',
startConnect: false
},
browserNoActivityTimeout: 60000,
captureTimeout: 120000,
customLaunchers: customLaunchers,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: Object.keys(customLaunchers),
singleRun: true
});
};

Starting Karma version 0.12 there are some more timeout settings added.
Adding them to my karma config resolved this issue for me.
browserDisconnectTimeout
Type: Number
Default: 2000
Description: How long does Karma wait for
a browser to reconnect (in ms). With a flaky connection it is pretty
common that browser disconnects but the actual execution is running
without any problems. Karma does not treat a disconnection as
immediate failure and rather wait browserDisconnectTimeout ms. If the
browser reconnect during that time, everything is fine.
-
browserDisconnectTolerance
Type: Number
Default: 0
Description: The number of disconnections tolerated.
The disconnectTolerance value represents the maximum number of tries a browser will attempt in case of disconnection. Usually any disconnection is considered as a failure, but this option allows to define a tolerance level when there is a flaky network link between the karma server and the browsers.
-
browserNoActivityTimeout
Type: Number
Default: 10000
Description: How long does Karma wait for a message from a browser before disconnecting it (in ms).
If, during the execution, Karma does not receive any message from a browser within browserNoActivityTimeout ms, it will disconnect the browser.
source: http://karma-runner.github.io/0.12/config/configuration-file.html
more tips: http://oligofren.wordpress.com/2014/05/27/running-karma-tests-on-browserstack/

Related

chromedriver Only local connections are allowed

I try to start tests by webdriver-manager and protractor.
Verify versions:
Google Chrome 73.0.3683.86
ChromeDriver 73.0.3683.68
start webdriver-manager webdriver-manager start
and start protractor
I got error by protractor
enviroment: test
[12:20:23] I/hosted - Using the selenium server at http://localhost:4444/wd/hub
[12:20:23] E/driverProvider - Error code: 135
[12:20:23] E/driverProvider - Error message: unknown error: Chrome failed to start: exited abnormally
[12:20:23] E/driverProvider - Error: unknown error: Chrome failed to start: exited abnormally
(unknown error: DevToolsActivePort file doesn't exist)
(The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
(Driver info: chromedriver=73.0.3683.68 (47787ec04b6e38e22703e856e101e840b65afe72),platform=Linux 4.9.0-8-amd64 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 172 milliseconds
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: 'dev', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.9.0-8-amd64', java.version: '1.8.0_212'
Driver info: driver.version: unknown
at Hosted.<anonymous> (/usr/lib/node_modules/protractor/built/driverProviders/driverProvider.js:69:23)
at Generator.throw (<anonymous>)
at rejected (/usr/lib/node_modules/protractor/built/driverProviders/driverProvider.js:5:65)
at process._tickCallback (internal/process/next_tick.js:68:7)
[12:20:23] E/launcher - Process exited with error code 135
and info by webdriver-manager
12:19:38.934 INFO [ActiveSessionFactory.apply] - Capabilities are: {
"browserName": "chrome",
"count": 1
}
12:19:38.947 INFO [ActiveSessionFactory.lambda$apply$11] - Matched factory org.openqa.selenium.grid.session.remote.ServicedSession$Factory (provider: org.openqa.selenium.chrome.ChromeDriverService)
Starting ChromeDriver 73.0.3683.68 (47787ec04b6e38e22703e856e101e840b65afe72) on port 15966
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
protractor.conf.js in project folder (where I execute command protractor --host https://MySite
let test_url = '';
let enviroment = process.env.NODE_ENV;
console.log('enviroment:', enviroment);
//console.log('process.env:', process.env);
let settings = {
seleniumAddress: 'http://localhost:4444/wd/hub',
//directConnect: true,
specs: ['./e2e/todo-spec.js'],
// Options to be passed to Jasmine-node.
params: {
host: 'http://localhost:3000'
},
capabilities: {
browserName: 'chrome'
},
onPrepare: function() {
// The require statement must be down here, since jasmine-reporters#1.0
// needs jasmine to be in the global and protractor does not guarantee
// this until inside the onPrepare function.
var jasmineReporters = require('jasmine-reporters');
jasmine.getEnv().addReporter(
new jasmineReporters.JUnitXmlReporter('xmloutput', true, true)
);
},
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000
}
}
if(process.env.hasOwnProperty('npm_config_host') && process.env.npm_config_host){
settings.params.host = process.env.npm_config_host
}
exports.config = settings;
In your chromeOptions, can you try adding --no-sandbox and --disable-dev-shm-usage and then try running the tests . Also try downgrading the browser version to see if the code is working as expected.
"chromeOptions": {
"args": ['--no-sandbox','--disable-dev-shm-usage'],
Remove seleniumAddress: fomr your config and add the below one.
exports.config = {
directConnect: true,
}
When you add dirctConnect=true you don't need to start the webdriver separately.
Hope it help you
Please make sure you have
127.0.0.1 localhost
in your /etc/hosts file.
To check it, you should go to the terminal and run
sudo vi /etc/hosts
type your user password and paste
127.0.0.1 localhost
to an empty row.
Additionally, please make sure you have ChromeDriver -or the driver of the browser you intend to use- is installed and your program knows the path of ChromeDriver.
You can follow the steps explained here https://www.browserstack.com/guide/run-selenium-tests-using-selenium-chromedriver.

How to run Protractor specs on IE 11?

I have been trying to run protractor specs on IE 11,with following conf.js:
multiCapabilities: [
{
'browserName': 'internet explorer',
version: 11,
'ignoreProtectedModeSettings': true
// 'idle-duration':10000,
},
}],
And added this as well:
seleniumArgs: 'C:/Users/LJQAuser/AppData/Roaming/npm/node_modules/protractor/node_modules/webdriver-manager/selenium/IEDriverServer.exe',
And set directConnect to : false
But still its showing error:
Error in console is:
[12:38:42] I/local - Starting selenium standalone server...
[12:38:43] E/launcher - Error: Error: Server terminated early with status 1
at earlyTermination.catch.e (C:\Users\LJQAuser\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\remote\index.js:252:52)
at :null:null
at process._tickCallback (internal/process/next_tick.js:188:7)
Closing report
[12:38:43] E/launcher - Process exited with error code 100
There is tons of issues with internet explorer. Probably you wont be able to run it successfully.
There is alot of manual steps also to be applied.
Here is some basic guide how to setup:
Protractor test in IE
https://qavalidation.com/2017/11/run-protractor-test-ie-internet-explorer.html/
Good luck!

How to debug JavaScript tests in JHipster applications using Karma?

I have a simple monolithic application generated using JHipster v4.10.1 with front-end using Angular 4.x. To run JavaScript unit tests, as suggested in the documentation I ran
./node_modules/karma/bin/karma start src/test/javascript/karma.conf.js --debug
The command runs the tests, reports coverage summary and exits, whether tests all pass or some test fail does not matter. Test run output does show at one point that the debug server is loaded:
21 11 2017 13:41:20.616:INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/
But because the command exits, the Karma debug server can not be accessed. How to run tests so that Karma console can be used in browser to debug?
Figured out that the magic flag is actually single-run which seems to be true by default. So the main command to run for JS debug is:
yarn test --single-run=false
which in turn runs
$ karma start src/test/javascript/karma.conf.js --single-run=false
With this the command will only exit with explicit kill e.g. with Ctrl+C or Z. Karma debug console can then be accessed on http://localhost:9876/debug.html (assuming default port is not already busy. If it is, test output should tell you which port was chosen).
Additionally you need to disable minimization (and also istanbul config - not sure why) so that you can breakpoint and step through the .ts code in debugger easily. I figured this is done by making following changes in webpack/webpack.test.js file:
Remove following istanbul config from module.rules array:
{
test: /src[/|\\]main[/|\\]webapp[/|\\].+\.ts$/,
enforce: 'post',
exclude: /(test|node_modules)/,
loader: 'sourcemap-istanbul-instrumenter-loader?force-sourcemap=true'
}
Add minimize: false to the LoaderOptionsPlugin under plugins array:
new LoaderOptionsPlugin({
minimize: false,
options: {
tslint: {
emitErrors: !WATCH,
failOnHint: false
}
}
})

Protractor does not close browser when a server is unavailable

I do e2e testing with protractor. When my application is running on a server the tests pass fine and a browser is closed afterward, however when the server is down the browser remains (Firefox, Chrome). It is OK on my local machine but I am experimenting with running tests on remote CI machine and afraid that the tests can spawn multiple browser windows if the server fails to run. How to make sure protractor closes the browser window in such situation?
Here is my configuration:
exports.config = {
allScriptsTimeout: 11000,
specs: [
'../test/e2e/*.js'
],
capabilities: {
'browserName': 'firefox'
},
baseUrl: 'http://localhost:8000/',
framework: 'jasmine',
jasmineNodeOpts: {
defaultTimeoutInterval: 30000
}
};
and the test is:
'use strict';
describe('typicaClient', function() {
browser.get('index.html');
it('test', function() {
expect('str').toMatch('str');
});
});
Protractor leaves browser open on those errors which it doesn't recognize and cannot handle.
Check out the example below. This error thrown by spawn() process is unhandled by Protractor and it exits with an error code - 199
describe('sample test', function(){
it('Sample Check', function(){
browser.get("http://www.protractortest.org/#/");
browser.sleep(5000);
var terminal = require('child_process').spawn('34e3545')
});
});
Output:
[18:26:46] I/local - Starting selenium standalone server...
[18:26:46] I/launcher - Running 1 instances of WebDriver
[18:26:46] I/local - Selenium standalone server started at http://192.168.1.5:61146/wd/hub
Started
[18:26:49] E/launcher - spawn 34e3545 ENOENT
[18:26:49] E/launcher - Error: spawn 34e3545 ENOENT
at exports._errnoException (util.js:873:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:178:32)
at onErrorNT (internal/child_process.js:344:16)
at nextTickCallbackWith2Args (node.js:442:9)
at process._tickCallback (node.js:356:17)
[18:26:49] E/launcher - Process exited with error code 199
To avoid these , handle gracefully the error at non-protractor commands
describe('sample test', function(){
it('Sample Check', function(){
browser.get("http://www.protractortest.org/#/");
browser.sleep(5000);
var terminal = require('child_process').spawn('34e3545').on('error', function(err) {
fail('Test is failing because we provided an invalid process')
});
});
});
Output in this case:
[18:57:22] I/local - Starting selenium standalone server...
[18:57:22] I/launcher - Running 1 instances of WebDriver
[18:57:22] I/local - Selenium standalone server started at http://192.168.1.5:49867/wd/hub
Started
F
Failures:
1) sample test Sample Check
Message:
Failed: Test is failing because we provided an invalid process
Stack:
Error: Failed: Test is failing because we provided an invalid process
at ChildProcess.<anonymous> (C:\Users\ayannam\WebstormProjects\demo\errorHandle.js:7:13)
at emitOne (events.js:77:13)
at ChildProcess.emit (events.js:169:7)
at Process.ChildProcess._handle.onexit (internal/child_process.js:198:12)
1 spec, 1 failure
Finished in 6.582 seconds
See it this case Un-handled exception is handled and Protractor throws an error code - 1 which is gracefully handled

Protractor test's within Webstorm has no Browser Connection

While trying to start the default protractor tests, WebStorm or protractor can not launch the default pages inside the Browser.
The Error Message is a simple Exception:
FA Jasmine spec timed out. Resetting the WebDriver Control Flow.
The setup for protractor is as follows:
The protractor.conf.js is as follows
exports.config = {
allScriptsTimeout: 11000,
specs: [
'*.js'
],
capabilities: {
'browserName': 'chrome'
},
baseUrl: 'http://localhost:8000/app/',
framework: 'jasmine2',
jasmineNodeOpts: {
defaultTimeoutInterval: 30000
}
};
and the tests are the default webstorm tests.
Configuration looks OK.
Please make sure you have started the local webserver on port 8000 (npm start) prior to running protractor - webserver needs to be serving up the application, so that Protractor can interact with it.
Also, make sure that web driver is installed (npm run update-webdriver)