How to set environment variable to run webdriverIO script - webdriver-io

I am running my webdriverIO test cases using command
npx wdio run .\wdio.conf.js --spec .\test\intel.test.js
Now I want to pass environment variable for the same like ENV=qa
If I run command like this ENV=qa npx wdio run .\wdio.conf.js --spec .\test\intel.test.js
Getting error:
ENV=qa : The term 'ENV=qa' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct
and try again. At line:1 char:1
ENV=qa npx wdio run .\wdio.conf.js --spec .\test\intel.test.js
is there any way to set environment variable when we are using npx to run test cases?

Checkout dotenv package -> https://www.npmjs.com/package/dotenv
and read this:
https://nodejs.dev/learn/how-to-read-environment-variables-from-nodejs

you can pass as like in the below command for user,key and baseurl which are all the allowed keys in wdio.conf.js.
npx wdio run .\wdio.conf.js --spec .\test\intel.test.js --user=automation
if you want to use any other parameters (like ENV as you mentioned), pls go with dotenv.

What I would do is set an environment variable in your console (that would work in CI as well depending on the tool your are using)
// In linux for example
export MY_VAR=foo
and in Webdriver.io simply access it with process.env like this
console.log(`MY_VAR value is: ${process.env.MY_VAR}`);
I get (last line)
...
[0-0] alwaysMatch: { browserName: 'chrome', acceptInsecureCerts: true },
[0-0] firstMatch: [ {} ]
[0-0] },
[0-0] desiredCapabilities: { browserName: 'chrome', acceptInsecureCerts: true }
[0-0] }
[0-0] 2022-11-18T16:59:50.392Z INFO webdriver: COMMAND maximizeWindow()
[0-0] 2022-11-18T16:59:50.393Z INFO webdriver: [POST] http://localhost:9515/session/d70c54abaefa7549da6e3946f2b26ce8/window/maximize
[0-0] MY_VAR value is: foo
Quite handy and easy.

Related

Protractor fails to find web-manager

I have protractor installed in project folder + web-manager (installed the same way).
The web-manager is started:
$npm-run webdriver-manager status
webdriver-manager: using global installed version 12.0.6
- selenium standalone version available: 3.8.1 [last]
- chromedriver version available: 2.35 [last]
- geckodriver version available: v0.19.1 [last]
- IEDriverServer is not present
However, when I run protractor
$ npm-run protractor conf.js
[15:22:12] I/launcher - Running 1 instances of WebDriver
[15:22:12] E/local - Error code: 135
[15:22:12] E/local - Error message: No update-config.json found. Run 'webdriver-manager update' to download binaries.
[15:22:12] E/local - Error: No update-config.json found. Run 'webdriver-manager update' to download binaries.
Here is my conf.js for protractor
exports.config = {
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome',
},
// Spec patterns are relative to the current working directly when
// protractor is called.
specs: ['tests/common/*.js'],
};
How do I fix the config/run protrator?
you need to run npm-run webdriver-manager update to install webdriver binary and selenium-standalon-server.jar if you never execute it, otherwise the command will update existed stuff.
After that, find update-config.json in node_modules\protractor\node_modules\webdriver-manager\selenium.
Its content should be like this:
{
"chrome": {
"last": "xxx\\node_modules\\protractor\\node_modules\\webdriver-manager\\selenium\\chromedriver_2.35.exe",
"all": ["xxx\\node_modules\\protractor\\node_modules\\webdriver-manager\\selenium\\chromedriver_2.35.exe"]
},
"standalone": {
"last": "xxx\\node_modules\\protractor\\node_modules\\webdriver-manager\\selenium\\selenium-server-standalone-3.9.0.jar",
"all": ["xxx\\node_modules\\protractor\\node_modules\\webdriver-manager\\selenium\\selenium-server-standalone-3.9.0.jar"]
},
"gecko": {
"last": "xxx\\node_modules\\protractor\\node_modules\\webdriver-manager\\selenium\\geckodriver-v0.19.1.exe",
"all": ["xxx\\node_modules\\protractor\\node_modules\\webdriver-manager\\selenium\\geckodriver-v0.19.1.exe"]
}
}
Then execute node_modules\.bin\webdriver-manager start to see will success or fail.
FYI, you need JDK 8 installed to start webdriver-manager.
Finally, found a solution using gulp.
The config below allows to run webmanager-update, webmanager-start and proptractor on by one.
gulp.js
var gulp = require('gulp'),
shell = require('gulp-shell'),
connect = require('gulp-connect'); // Webserver
protractor = require('gulp-protractor').protractor,
webdriver_standalone = require('gulp-protractor').webdriver_standalone,
webdriver_update = require('gulp-protractor').webdriver_update;
gulp.task('webdriver_update', webdriver_update);
gulp.task('webdriver_standalone', webdriver_standalone);
gulp.task('e2e', ['webdriver_update'], function() {
gulp.src(["tests/protractor/*.js"])
.pipe(protractor({
configFile: "protractor.conf.js",
args: [
//'--baseUrl', 'http://127.0.0.1:8000',
// '--suite', 'login',
// '--params.environment', 'test'
]
}))
.on('error', function(e) { throw e })
});
protractor.conf.js
exports.config = {
seleniumServerJar: './node_modules/webdriver-manager/selenium/selenium-server-standalone-3.9.0.jar',
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome',
},
};
(using URL for selenium server is impotant)
Launch command:
gulp e2e

phantom JS configuration when used with InternJS

I want to use phantomJS with Intern for functional testing.
I Installed phantomJS and ran the command "phantomjs --webdriver 4444", it ran successfully.
Then tried to run intern-runner with the command "intern-runner config=tests/intern" -file tests/intern is shown at the end of the post-.
but i keep getting the error
intern-runner config=tests/intern
Listening on 0.0.0.0:9000
Tunnel started
Suite phantomjs on any platform FAILED
UnknownError: [POST http: //localhost:4444/wd/hub/session / {"desiredCapabilities":{"browserName":"phantomjs","name":"tests/intern","idle-timeout":60}}] An unknown server-side error occurred while processing the command.
on intern.
and the error
[ERROR - 2015-10-14T10:14:35.611Z] RouterReqHand - _handle.error - {"message":"{
\"headers\":{\"Connection\":\"close\",\"Host\":\"localhost:4444\",\"accept\":\"a
pplication/json,text/plain;q=0.9\",\"content-length\":\"91\",\"content-type\":\"
application/json;charset=UTF-8\",\"user-agent\":\"dojo/2.0.0-dev Node.js/4.1.2\"
},\"httpVersion\":\"1.1\",\"method\":\"POST\",\"url\":\"/session\",\"urlParsed\"
:{\"anchor\":\"\",\"query\":\"\",\"file\":\"session\",\"directory\":\"/\",\"path
\":\"/session\",\"relative\":\"/session\",\"port\":\"\",\"host\":\"\",\"password
\":\"\",\"user\":\"\",\"userInfo\":\"\",\"authority\":\"\",\"protocol\":\"\",\"s
ource\":\"/session\",\"queryKey\":{},\"chunks\":[\"session\"]}}","name":"Missing
Command Parameter","line":85,"sourceId":65775352,"sourceURL":":/ghostdriver/req
uest_handlers/session_manager_request_handler.js","stack":"Missing Command Param
eter: {\"headers\":{\"Connection\":\"close\",\"Host\":\"localhost:4444\",\"accep
t\":\"application/json,text/plain;q=0.9\",\"content-length\":\"91\",\"content-ty
pe\":\"application/json;charset=UTF-8\",\"user-agent\":\"dojo/2.0.0-dev Node.js/
4.1.2\"},\"httpVersion\":\"1.1\",\"method\":\"POST\",\"url\":\"/session\",\"urlP
arsed\":{\"anchor\":\"\",\"query\":\"\",\"file\":\"session\",\"directory\":\"/\"
,\"path\":\"/session\",\"relative\":\"/session\",\"port\":\"\",\"host\":\"\",\"p
assword\":\"\",\"user\":\"\",\"userInfo\":\"\",\"authority\":\"\",\"protocol\":\
"\",\"source\":\"/session\",\"queryKey\":{},\"chunks\":[\"session\"]}}\n at :
/ghostdriver/request_handlers/session_manager_request_handler.js:85\n at :/gh
ostdriver/request_handlers/session_manager_request_handler.js:44\n at :/ghost
driver/request_handlers/router_request_handler.js:70","stackArray":[{"sourceURL"
:":/ghostdriver/request_handlers/session_manager_request_handler.js","line":85},
{"sourceURL":":/ghostdriver/request_handlers/session_manager_request_handler.js"
,"line":44},{"sourceURL":":/ghostdriver/request_handlers/router_request_handler.
js","line":70}]}
on phantomjs - this error appears after running the intern-runner-.
does anyone know what the problem is?.
p.s. I'm using phantomJS v.1.9.8
tests/intern :
define({
proxyPort: 9000,
proxyUrl: 'http://localhost:9000/',
environments: [
{ browserName: 'phantomjs' }
],
maxConcurrency: 3,
useSauceConnect: false,
loaders: {
'host-browser': 'node_modules/requirejs/require.js'
},
tunnel: 'NullTunnel',
functionalSuites: [ 'tests/functional/modetest' ],
});
PhantomJS 1 is ancient (it uses a version of WebKit from 2012) and not supported. You must use PhantomJS 2+ with Intern.

Protractor : ERROR - Unable to start a WebDriver session

I wrote test cases three months back at that time they worked fine now i want to run those test cases in another system so i did basic setup. When i try to run protractor test case now they are failing with 'Unable to start a WebDriver session'. I have tried so many solutions but they didn't work for me.
Here i am attaching my protractor.conf.js file and error details.
protractor.conf.js
'use strict';
exports.config = {
seleniumAddress: 'http://127.0.0.1:4444/wd/hub',
baseUrl: 'http://localhost:' + (process.env.PORT || '3036'),
chromeOnly: true,
// To get the maximimum test screen size
onPrepare: function() {
browser.driver.manage().window().maximize();
},
// list of files / patterns to load in the browser
specs: [
'e2e/attributeSection/search_spec.js', 'e2e/attributeSection/create_spec.js',
'e2e/attributeSection/edit_spec.js', 'e2e/attribute/search_spec.js',
'e2e/attribute/create_spec.js', 'e2e/attribute/edit_spec.js',
'e2e/classification/search_spec.js', 'e2e/classification/create_spec.js',
'e2e/classification/edit_spec.js', 'e2e/classificationGroup/create_spec.js',
'e2e/classificationGroup/edit_spec.js'
],
exclude: [],
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
binary: 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',
args: [],
extensions: [],
}
},
framework: 'jasmine',
jasmineNodeOpts: {
defaultTimeoutInterval: 60000
}
};
Error in console
Using the selenium server at http://127.0.0.1:4444/wd/hub
[launcher] Running 1 instances of WebDriver
ERROR - Unable to start a WebDriver session.
C:\Users\Cronj- 4\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\http\index.js:145
callback(new Error(message));
^
Error: ECONNREFUSED connect ECONNREFUSED
at ClientRequest.<anonymous> (C:\Users\Cronj-4\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\http\index.js:145:16)
at ClientRequest.emit (events.js:95:17)
at Socket.socketErrorListener (http.js:1552:9)
at Socket.emit (events.js:95:17)
at net.js:441:14
at process._tickCallback (node.js:442:13)
From: Task: WebDriver.createSession()
at Function.webdriver.WebDriver.acquireSession_ (C:\Users\Cronj-4\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\webdriver\webdriver.js:155:22)
at Function.webdriver.WebDriver.createSession (C:\Users\Cronj-4\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\webdriver\webdriver.js:129:30)
at [object Object].Builder.build (C:\Users\Cronj-4\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\builder.js:416:22)
at [object Object].DriverProvider.getNewDriver (C:\Users\Cronj-4\AppData\Roaming\npm\node_modules\protractor\lib\driverProviders\driverProvider.js:38:7)
at [object Object].Runner.createBrowser (C:\Users\Cronj-4\AppData\Roaming\npm\node_modules\protractor\lib\runner.js:180:37)
at C:\Users\Cronj-4\AppData\Roaming\npm\node_modules\protractor\lib\runner.js:257:21
at _fulfilled (C:\Users\Cronj-4\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:797:54)
at self.promiseDispatch.done (C:\Users\Cronj-4\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:826:30)
at Promise.promise.promiseDispatch (C:\Users\Cronj-4\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:759:13)
Could anyone help me out? Thanks in advance
I believe the "chromeOnly" option got deprecated in v2.0.0.
chromeOnly: true,
This used to mean use "direct" mode without a selenium server. But since both firefox and chrome support direct mode, the property was renamed to "directConnect". So change that line to:
directConnect: true,
In this mode you don't need a selenium server, so you can drop the seleniumAddress property which is just confusing folks.
See https://github.com/angular/protractor/pull/1933/files
I ran webdriver-manager start in one command prompt and protractor in another command prompt then only test cases started running

protractor could not find protractor/selenium/chromedriver.exe at codeship

i'm trying to configure the integration to run portractor tests.
I'm using grunt-protractor-runner task
with following configuration:
protractor: {
options: {
configFile: "protractor.conf.js", //your protractor config file
keepAlive: true, // If false, the grunt process stops when the test fails.
noColor: false, // If true, protractor will not use colors in its output.
args: {
// Arguments passed to the command
}
},
run: {},
chrome: {
options: {
args: {
browser: "chrome"
}
}
}
}
and here is grunt task which i use for running the protractor after the server is running:
grunt.registerTask('prot', [
'connect:test',
'replace:includemocks',//for uncommenting angular-mocks reference
'protractor:run',
'replace:removemocks',//for commenting out angular-mocks reference
]);
It is running well on my local machine, but at codeship i'm getting following error:
Error: Could not find chromedriver at /home/rof/src/bitbucket.org/myrepo/myFirstRepo/node_modules/grunt-protractor-runner/node_modules/protractor/selenium/chromedriver.exe
Which i guess, a result of not having this "chromedriver.exe" at this path.
How can i solve it in codeship environment?
Thanks forwards
Add postinstall to your package.json file and that way npm install will take care of placing the binaries for you ahead of time:
"scripts": {
"postinstall": "echo -n $NODE_ENV | \
grep -v 'production' && \
./node_modules/protractor/bin/webdriver-manager update || \
echo 'will skip the webdriver install/update in production'",
...
},
And don't forget to set NODE_ENV ... not setting it at all will result in echo 'will skip the webdriver install/update in production' piece running. Setting it to dev or staging will get desired results.
Short answer (pulkitsinghal gave the original solution):
./node_modules/grunt-protractor-runner/node_modules/protractor/bin/webdriver-manager update
I'm one of the founders at Codeship.
The error seems to be because you are trying to use the exe file, but we're on Linux on our system. Did you hardcode that executable?
Could you send us an in-app support request so we have a link to look at and can help you fix this?

Setting up Continuous Integration of Protractor using Jenkins

I am writing automation test scripts using Protractor and now I need to set up the CI for this using Jenkins.
Tasks it needs to perform are:
Starting the selenium standalon server.
Starting the test using conf.js file.
Stopping the selenium standalone server.
Can anyone help in this regard?
I created a small bash script to do this.
# start selenium
./node_modules/protractor/bin/webdriver-manager start > /dev/null 2>&1 &
# wait until selenium is up
while ! curl http://localhost:4444/wd/hub/status &>/dev/null; do :; done
# run the build
grunt cibuild --force
# stop selenium
curl -s -L http://localhost:4444/selenium-server/driver?cmd=shutDownSeleniumServer > /dev/null 2>&1
This script is invoked from a free-style project in jenkins (Build > Execute shell)
Then the test result report is generated by reading the protractor test results. Hence, you have to produce junit reports from protractor, (look here) :
onPrepare: function() {
// The require statement must be down here, since jasmine-reporters
// needs jasmine to be in the global and protractor does not guarantee
// this until inside the onPrepare function.
require('jasmine-reporters');
jasmine.getEnv().addReporter(
new jasmine.JUnitXmlReporter('xmloutput', true, true));
},
To make the report visible in jenkins i add a post build action in the job: Publish JUnit test result report:
Alternatively, you could run this as a Grunt Task. First install grunt on Jenkins. Install the NPM packages for protractor_webdriver and protractor. Setup the configuration file to point the the node_module path and config file paths.
http://sideroad.secret.jp/articles/grunt-on-jenkins/
Then install protractor node modules. The Gruntfile would look similar to this. I created a test directory where the conf and spec files would be located.
module.exports = function (grunt) {
grunt.initConfig({
protractor_webdriver: {
your_target: {
options: {
path: 'node_modules/protractor/bin/',
command: 'webdriver-manager start'
}
}
},
protractor: {
options: {
configFile: "node_modules/protractor/referenceConf.js", // Default config file
keepAlive: true, // If false, the grunt process stops when the test fails.
noColor: false, // If true, protractor will not use colors in its output.
args: {
// Arguments passed to the command
}
},
your_target: {
options: {
configFile: "test/conf.js", // Target-specific config file
args: {} // Target-specific arguments
}
}
}
});
grunt.registerTask('p:test', [
'protractor_webdriver',
'protractor'
]);
});
The newest protractor allows you to run the selenium standalone server directly from the conf.js (or whatever protractor entry point you have).
comment out (or delete) the seleniumAddress: 'http://localhost:4444/wd/hub', line, and replace it with seleniumServerJar: './node_modules/protractor/selenium/latest.jar'.
latest.jar isn't installed by default, I created it as a symlink to the latest version installed via npm install protractor --save. This gives longer life to my conf.js files in the same directory.
Within the ./node_modules/protractor/selenium/ folder I ran ln -s selenium-server-standalone-2.48.2.jar latest.jar
You can use Gulp which is far simpler.
After installing gulp in Jenkins System , you may install the npm dependencies(npm install) & run gulp tasks directly as windows batch command in Jenkins as below:
In the background to make selenium server up and running and providing various other parameters , you may use packages like 'gulp-angular-protractor' in the gulpfile.js as below:
gulpfile.js
'use strict';
var gulp = require('gulp'),
gulpProtractorAngular = require('gulp-angular-protractor'),
gulpStart = gulp.Gulp.prototype.start,
currentStartTaskName;
gulp.Gulp.prototype.start = function (task) {
currentStartTaskName = task;
gulpStart.apply(this, arguments);
};
function executeWebTests(suiteName, appName) {
return gulp.src([])
.pipe(gulpProtractorAngular({
'configFile': './conf.js',
'debug': false,
'autoStartStopServer': true,
args: [
'--suite', suiteName,
'--capabilities.browserName', 'chrome',
'--params.APPNAME', appName,
'--params.SUITENAME', currentStartTaskName,
'--capabilities.platformName', 'Windows'],
keepAlive: false
}))
.on('error', function (e) {
console.log('Ended with below ERROR::',e);
process.exit(1);
})
.on('end', function () {
console.log('Test complete');
process.exit();
});
}
gulp.task('RegressionSuiteTask', function () {
executeWebTests('regressionTests,','Application_Name');
});
conf.js
suites: {
regressionTests: ['testCases/**/*.js']//will run all specs in subfolders
},
I know this already resolved and want to target for beginner to create Jenkins job and running test. I suggest to use selenium-server-standalone jar in configuration file and call configuration file from Jenkins.
conf.js
..
exports.config = {
//seleniumAddress: 'http://localhost:4444/wd/hub',
seleniumServerJar: 'node_modules/protractor/node_modules/webdriver-manager/selenium/selenium-server-standalone-3.5.3.jar',
....
//html reporter logic
.....
Creating Jenkins Job
Install node js on Jenkins Server
Install Html Publisher Plugin for end to end testing report
Create Freestyle Project or whatever your needs
Go to Build Section -> Add build step and choose Execute Windows
batch command if Jenkins server in Windows otherwise choose Execute
Shell for Linux
Call conf.js (install packages and call your configuration file)
For reporting Got to Post-Build Actions Section -> Add Publish Html
Reports and call your report file (file assuming from root of your
project)
However you can customize execution command using gulp or similar other packages. Thanks