How to call global env variable for gulp protractor - protractor

This is gulpfile:
gulp.task(
'protractor', function () {
var configObj = {
configFile: config.test + 'protractor.conf.js'
};
configObj['args'] =[];//to be able to add multiple parameters
if (argv.suite) {
configObj['args'].push (
'--suite',
argv.suite
);
}
if (argv.env) {
if(argv.env.includes("q")){//qa
argv.baseUrl = "http://xx.qa.yy.com:8080";
}
else{//prod
if(argv.env.includes("p")){
argv.baseUrl = "https://xx.yy.com";
}
else{//local
argv.baseUrl = "localhost:8080";
}
}
configObj['args'] .push(
'--baseUrl',
argv.baseUrl
);
}
return gulp.src([])
.pipe(plumber({errorHandler: handleErrors}))
.pipe(protractor(configObj))
.on(
'error', function () {
gutil.log('E2E Tests failed');
process.exit(1);
}
);
}
);
so, in protractor test classes, i can get baseurl with that for exaple
this.getBaseUrl = function () {
return browser.baseUrl;
};
,
because i set here
configObj['args'] .push(
'--baseUrl',
argv.baseUrl
);
but i cant get env. it is set here
from console command
gulp protractor --env l --suite logout
i can see in consloeoutput of that
argv.env
but i cant call from protractor it. I tried browser.env
but did not work. how can i do this?
also i use yargs
var argv = require('yargs')//setting default enviroment to qa for testing
.default({ env : 'qa' })
.argv;

There is no env global variable or command line option in protractor, You have to pass it as a paramater using params. You can do something like this-
if (argv.params.env) {
if(argv.params.env.includes("q")){//qa
argv.baseUrl = "http://xx.qa.yy.com:8080";
}
else{//prod
if(argv.params.env.includes("p")){
argv.baseUrl = "https://xx.yy.com";
}
else{//local
argv.baseUrl = "localhost:8080";
}
}
Now from console command you can invoke it
gulp protractor --params.env 'test' --suite logout
You can also access it calling browser.params.env
You can always set globals in protractor in config file:
exports.config = {
//other config options
params: {
env: 'qa'
}
};
And pass values to the global variables through command line as-
protractor conf.js --params.env 'dev'

Related

Protractor - How to pass variable inside browser.get() function?

I have saved a url in config.js file in runtime, now i have my url in "browser.params.tempVar". If i use it directly in script like browser2.get(browser.params.tempVar); it is not working, Could someone suggest how to use variable in browser.get() function.
What you're doing is the correct way.
Double check that you've got the param set up correctly in config.js:
exports.config = {
...
params: {
...
tempVar: "tempVar"
...
}
...
}
Then use the default protractor browser to retrieve the value:
...
const prot = require("protractor");
const browser = prot.browser;
const myParam = browser.params.tempVar;
browser2.get(myParam);
or in TS:
...
import {browser} from 'protractor';
const myParam = browser.params.tempVar;
browser2.get(myParam);
Could can also override this param value by command-line argument if needed:
Normal run:
npx protractor conf.js
Override param:
npx protractor conf.js --params.tempVar="newVar"

Can not transform code with babel transform with config file

This is the config file:
{
"presets": [
"#babel/preset-env"
],
"plugins": [
"#babel/plugin-transform-modules-commonjs"
]
}
This is the command:
npx babel src/* --out-dir build
The CLI output is
src/script.js -> build\src\script.js
The output script file is identical to the input script file.
This is the node.js file:
const babel = require('#babel/core');
const fs = require('fs');
fs.writeFileSync(
'build/index.js',
babel.transformFileSync(
'src/index.js',
{
plugins: ["#babel/plugin-transform-modules-commonjs"]
}
).code
);
The output script file's content is what is expected.
I used this as input:
const test = 0;
export default { test };
This is the output from the CLI command shown above.
const test = 0;
export default { test };
This is the output from the NodeJS file shown above (which is my expected output from the CLI).
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var test = 0;
var _default = {
test: test
};
exports["default"] = _default;
Q: Can you you babel CLI to transform code?
We have used babel-node in scenario where we want to transpile. https://babeljs.io/docs/en/next/babel-node.html
npx babel-node src/* --out-dir build
Not sure why transform, which is an async function, is being used inside a synchroous, blocking execution. Instead use transformSync and .code
fs.writeFileSync(
'build/script.js',
babel.transformSync(
fs.readFileSync('src/script.js').toString('utf8'),
{
plugins: ["#babel/plugin-transform-modules-commonjs"]
}
).code
);
Or even more, you can use transformFileSync:
fs.writeFileSync(
'build/script.js',
babel.transformFileSync(
'src/script.js',
{
plugins: ["#babel/plugin-transform-modules-commonjs"]
}
).code
);

How can we use the On Prepare function in config File while i am trying to run multiple Spec files

In the Config File i am using the On Prepare Function for the purpose of assigning the property data test id as value
But for the first spec file execution the on prepare is picked up
but on the next execution of the Spec , the on prepare function is not getting picked up
import { Config } from "protractor/built/config";
import { by } from "protractor";
// import { encode } from "punycode";
function encode(file) {
var stream = require('fs').readFileSync(file);
return new Buffer(stream).toString('base64');
}
export let config: Config = {
// The address of a running selenium server.
//seleniumAddress: 'http://localhost:4444/wd/hub',
directConnect:true,
allScriptsTimeout:1500000,
// Capabilities to be passed to the webdriver instance.
capabilities: {
browserName: 'chrome',
'chromeOptions': {
'extensions': [encode('C:/Users/koanand/Documents/Protractor/ASR/2.2.9_0.crx')]
}
},
onPrepare: function () {
by.addLocator('testId', function(value, parentElement) {
parentElement = parentElement || document;
var nodes = parentElement.querySelectorAll('[data-test-id]');
return Array.prototype.filter.call(nodes, function(node) {
return (node.getAttribute('data-test-id') === value);
});
});
},
// Spec patterns are relative to the configuration file location passed
// to protractor (in this example conf.js).
// They may include glob patterns.
specs: ['C:/Users/anand/Documents/Protractor/ASR/TS-Output/specs/directasr.js',
'C:/Users/anand/Documents/Protractor/ASR/TS-Output/specs/products.js'
],
// Options to be passed to Jasmine-node.
jasmineNodeOpts: {
showColors: true, // Use colors in the command line report.
defaultTimeoutInterval : 150000
}
};
i am observing the below error
Message:
Failed: protractor_1.by.testID is not a function
Stack:
TypeError: protractor_1.by.testID is not a function
at new productlist (C:\Users\koanand\Documents\Protractor\ASR\pageobject\productlist.ts:19:45)
at product.selectingproductlist (C:\Users\koanand\Documents\Protractor\ASR\specs\classproductlist.ts:14:32)
at UserContext.<anonymous> (C:\Users\koanand\Documents\Protractor\ASR\specs\products.ts:21:21)
at C:\Users\koanand\Documents\Protractor\ASR\node_modules\jasminewd2\index.js:108:15
at new ManagedPromise (C:\Users\koanand\Documents\Protractor\ASR\node_modules\selenium-webdriver\lib\promise.js:1077:7)
at ControlFlow.promise (C:\Users\koanand\Documents\Protractor\ASR\node_modules\selenium-webdriver\lib\promise.js:2505:12)
at schedulerExecute (C:\Users\koanan
d\Docume
Use BeforeAll() in each spec file & write whatever you want to execute before each spec starts
May following link help you to clear your doubts for onPrepare and what to use in pace of it.
OnPrepare function in Protractor

gulp task with gulp-run-command doesn't work properly

I'm trying to run json-server in a gulp task and I'm checking if the server runs, with the function portInUse.
Like this:
var gulputil = require('gulp-util')
var run = require('gulp-run-command').default
var gulp = require('gulp')
const args = [
'json-server --watch .\\src\\main\\app\\reactjs\\api\\db.json --port 3005'
]
var net = require('net');
var portInUse = function(port, callback) {
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
});
server.listen(port, '127.0.0.1');
server.on('error', function (e) {
callback(true);
});
server.on('listening', function (e) {
server.close();
callback(false);
});
};
gulp.task("initLocalJsonServer", function() {
portInUse(3005, function(returnValue) {
gulputil.log('1 ' + returnValue);
});
run(args);
portInUse(3005, function(returnValue) {
gulputil.log('2 ' + returnValue);
});
});
That command that is the value of args here, works as intended when I run it in command line, so there's nothing wrong with the command or json-server itself. If I run it, I get to see the json-server at localhost:3005
Now the output from the portInUse function indicates that the server starts, as the output is:
[10:33:56] 1 false
[10:33:56] 2 true
But if I go to localhost:3005 after the gulp tasks are done, I can't see any server running. What might be the reason?

Setting up PostCSS

I am just trying to set up PostCSS and integrate it into my recent workflow. But somehow I don't seem to get it work.
I am using A Mac and gulp as a task runner.
This is the erro I get when starting my watch task:
TypeError: $.postcss is not a function
And this is what my gulpfile.js looks like:
var gulp = require('gulp');
var $ = require('gulp-load-plugins')({
rename: {
'browser-sync': 'browserSync',
'gulp-postcss': 'postcss',
},
pattern: ['gulp-*', 'gulp.*', 'del', 'run-sequence', 'browser-sync'],
DEBUG: false
});
var targetPath = 'dist';
var useBrowserSync = $.util.env.browserSync || true;
gulp.task('sass', function(){
return gulp.src('src/scss/*.{scss,sass,css}')
.pipe($.postcss([
require('precss')()
], {syntax: require('postcss-scss')}))
.pipe(gulp.dest(targetPath + '/public/assets/css'))
.pipe( $.if( useBrowserSync , $.browserSync.stream() ) );
});
gulp.task('watch', ['sass'], function(){
if( useBrowserSync ){
$.browserSync.create();
$.browserSync.init({
proxy: 'localhost/my_project/dist/public/'
});
}
gulp.watch('src/scss/*.{scss,sass,css}', ['sass']);
});
What is going wrong?