How do I pass browser as a command line parameter when launching tests - webdriver

I am trying to run multi-browser testing against Chrome and Firefox.
I would like to only run one browser at a time. So I would like to pass into test a command line parameter --browser chrome for example and have it only run the chrome browser.
I read somewhere that I could do a params: {} section of my protractor.config.js.
So I added the following:
params: {
browser: multiCapabilities.browserName,
},
The error that I am getting is below:
ReferenceError: multiCapabilities is not defined
at Object.<anonymous> (/Users/csalisbury/src/helios/protractor.config.js:91:18)
at Module._compile (internal/modules/cjs/loader.js:678:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:689:10)
at Module.load (internal/modules/cjs/loader.js:589:32)
at tryModuleLoad (internal/modules/cjs/loader.js:528:12)
at Function.Module._load (internal/modules/cjs/loader.js:520:3)
at Module.require (internal/modules/cjs/loader.js:626:17)
at require (internal/modules/cjs/helpers.js:20:18)
at ConfigParser.addFileConfig (/Users/csalisbury/src/helios/node_modules/protractor/built/configParser.js:135:26)
at Object.initFn [as init] (/Users/csalisbury/src/helios/node_modules/protractor/built/launcher.js:93:22)
There is a multiCapabilities section defined. I also tried this with capabilities and got the same message.
What am I doing incorrectly here?
Here is my protractor.config.js
exports.config = {
suites: {
<test suites go here>
},
baseUrl: baseUrl,
directConnect: false,
allScriptsTimeout: 25 * 1000,
jasmineNodeOpts: {
defaultTimeoutInterval: 90 * 1000
},
getPageTimeout: 120 * 1000,
capabilities: {
browserName: 'chrome',
seleniumAddress: seleniumServer,
platform: 'ANY',
version: 'ANY',
chromeOptions: {
args: ['--no-sandbox', '--test-type=browser', '--lang=en', '--window-size=1680,1050'],
prefs: {
'credentials_enable_service': false,
'profile': {
'password_manager_enabled': false
},
download: {
prompt_for_download: false,
directory_upgrade: true,
default_directory: 'C:\\downloads\\'
},
},
},
loggingPrefs: { browser: 'SEVERE' }
},
capabilities: {
browserName: 'firefox',
'moz:firefoxOptions': {
args: ['--safe-mode'],
binary: '/Applications/Firefox.app/Contents/MacOS/firefox'
},
seleniumAddress: seleniumServer,
},
framework: 'jasmine2',
onPrepare: function() {
//Set Up a JUnit XML Reporter - Makes a nice test results area and trend graph in Jenkins
var jasmineReporters = require('jasmine-reporters');
jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({
consolidateAll: true,
savePath: 'report',
filePrefix: 'xmloutput'
}));
//Setup screenshots
jasmine.getEnv().addReporter(reporter);
browser.get(browser.baseUrl);
},
// Setup the report before any tests start
beforeLaunch: function() {
return new Promise(function(resolve) {
reporter.beforeLaunch(resolve);
});
},
// Close the report after all tests finish
afterLaunch: function(exitCode) {
return new Promise(function(resolve) {
reporter.afterLaunch(resolve.bind(this, exitCode));
});
},
};

browserName is set using capabilities - both for command line and in your config. So to set that with command line, it's just:
protractor conf.js --capabilities.browserName='firefox'
Values passed from the command line will override what is set in the config, so for example you could leave chrome as the default browser:
exports.config = {
capabilities: {
browserName: 'chrome'
}
}
And then to override chrome and run firefox, you would just pass in browserName as shown above.
Or if you want to avoid command line options and just run each browser sequentially, you can use multiCapabilities and limit the number of maxSessions allowed.
multiCapabilities: [
{ browserName: 'chrome' },
{ browserName: 'firefox' },
],
maxSessions: 1,
Source: protractor config

Related

How to connect google analytics to Nuxt3 app?

I have a problem. I try to connect my Nuxt3 app with Google Analytics.
right now I do it by adding to nuxt.config.ts following code
export default defineNuxtConfig({
buildModules: [
'#nuxtjs/google-analytics'
],
googleAnalytics: {
id: process.env.GOOGLE_ANALYTICS_ID
},
})
but unfortunately I get following error when I try to build my app
ERROR Error compiling template: { 17:53:04
ssr: false,
src: 'C:\\Users\\szczu\\Elektryk\\node_modules\\#nuxtjs\\google-analytics\\lib\\plugin.js',
fileName: 'google-analytics.js',
options: {
dev: true,
debug: {
sendHitTask: true
},
id: undefined
},
filename: 'google-analytics.js',
dst: 'C:/Users/szczu/Elektryk/.nuxt/google-analytics.js'
}
ERROR serialize is not defined 17:53:04
at eval (eval at <anonymous> (node_modules\lodash.template\index.js:1550:12), <anonymous>:7:1)
at compileTemplate (/C:/Users/szczu/Elektryk/node_modules/#nuxt/kit/dist/index.mjs:493:45)
at async /C:/Users/szczu/Elektryk/node_modules/nuxt3/dist/chunks/index.mjs:1296:22
at async Promise.all (index 11)
at async generateApp (/C:/Users/szczu/Elektryk/node_modules/nuxt3/dist/chunks/index.mjs:1295:3)
at async _applyPromised (/C:/Users/szczu/Elektryk/node_modules/perfect-debounce/dist/index.mjs:54:10)
Does anyone have an idea how to fix it?
Try the vue-vtag-next package as a plugin
yarn add --dev vue-gtag-next
Create a plugin file plugins/vue-gtag.client.js
import VueGtag from 'vue-gtag-next'
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.use(VueGtag, {
property: {
id: 'GA_MEASUREMENT_ID'
}
})
})
Late reply, but i would like to add for any future viewers.
The above solution only worked for me when the $router was passed. Please find below sample code.
Please also note:
The package being used, 'vue-gtag' instead of 'vue-gtag-next'.
You have to pass config object instead of property for the 'vue-gtag' package
import VueGtag from 'vue-gtag'
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.use(VueGtag, {
config: {
id: 'GA_MEASUREMENT_ID',
},
}, nuxtApp.$router)
})
found this solution https://github.com/nuxt/framework/discussions/5702
.. And also you may use nuxt.config to provide app.head.script with children attribute on the app level:
import { defineNuxtConfig } from "nuxt";
export default defineNuxtConfig({
app: {
head: {
script: [{ children: 'console.log("test3");' }],
},
},
});
import VueGtag from 'vue-gtag-next'
export default defineNuxtPlugin(async (nuxtApp) => {
const { data: { value: {google_id, google_sv, yandex_id, privacy_policy} } } = await useMyApi("/api/main/site-metriks/");
nuxtApp.vueApp.use(VueGtag, {
property: {
id: google_id
}
})
})
For Nuxt 3:
Install vue-gtm: npm i #gtm-support/vue-gtm
Create file in /plugins/vue-gtm.client.ts
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.use(createGtm({
id: 'GTM-ID',
defer: false, // Script can be set to `defer` to speed up page load at the cost of less accurate results (in case visitor leaves before script is loaded, which is unlikely but possible). Defaults to false, so the script is loaded `async` by default
compatibility: false, // Will add `async` and `defer` to the script tag to not block requests for old browsers that do not support `async`
nonce: '2726c7f26c', // Will add `nonce` to the script tag
enabled: true, // defaults to true. Plugin can be disabled by setting this to false for Ex: enabled: !!GDPR_Cookie (optional)
debug: true, // Whether or not display console logs debugs (optional)
loadScript: true, // Whether or not to load the GTM Script (Helpful if you are including GTM manually, but need the dataLayer functionality in your components) (optional)
vueRouter: useRouter(), // Pass the router instance to automatically sync with router (optional)
//ignoredViews: ['homepage'], // Don't trigger events for specified router names (optional)
trackOnNextTick: false, // Whether or not call trackView in Vue.nextTick
}))
})
Nuxt would automatically pick up this plugin and you're done.

k6 environmental variables results in GO error "invalid character"

k6 docs make using environmental variables very simple and I tried following their instructions, but I get a GO error when I try to run it:
ERRO[0000] GoError: parse https://${__ENV.TARGET_ENV}-api.mycompany.com/v1/managers/259999/properties": invalid character "{" in host name".
I don't see an extra bracket anywhere. This script was working fine when I had the url as https://green-api.mycompany.com/v1/managers/259999/properties. Am I possibly missing an import or dependency somewhere? All I am trying to do is get it working to where when i type k6 run --env TARGET_ENV=green propertiesScript.js, it executes against http://green-api.mycompany.com/v1/managers/259999/properties. Here is the file:
import { check } from "k6";
export let options = {
thresholds: {
http_req_duration: ["p(90)<300"], // 95% of requests should be below 200ms
Errors: ["count<100"],
},
};
export default function () {
var url =
"https://${__ENV.TARGET_ENV}-api.mycompany.com/v1/managers/259999/properties";
const params = {
headers: {
"X-App-Token": "<our app token>",
"X-Auth-Token":
"<our auth token>",
accept: "application/json",
},
};
let res = http.get(url, params);
console.log(res.body);
console.log(JSON.stringify(res.headers));
check(res, {
"status is 200": (r) => r.status === 200,
});
}
I also tried adding scenarios and adjusting the body of my file. These are the scenarios:
thresholds: {
http_req_duration: ["p(90)<300"], // 95% of requests should be below 200ms
Errors: ["count<100"],
},
scenarios: {
pod_green: {
tags: { my_custom_tag: "green" },
env: { MYVAR: "green" },
executor: "shared-iterations",
},
pod_red: {
tags: { my_custom_tag: "red" },
env: { MYVAR: "red" },
executor: "shared-iterations",
},
staging: {
tags: { my_custom_tag: "staging" },
env: { MYVAR: "staging" },
executor: "shared-iterations",
},
},
};
Then I edited my export default function and I was able to get that script to run, but it runs against every single environment.
You need to use backticks when you set the url variable for string interpolation to work in template literals. See the documentation.
So in your case you should have:
var url =
`https://${__ENV.TARGET_ENV}-api.mycompany.com/v1/managers/259999/properties`;

nightwatch.js / Saucelabs - click() not working [ An error occurred while running .click() command on <Element [name=#login_submitButton]>]

I have been trying to run e2e test cases for a React app using Nightwatch.js + Saucelabs, but is facing the below error while .click() method executes.
Error:
An error occurred while running .click() command on : {"status":-1,"state":"","value":"{\"value\": {\"stacktrace\": \"Backtrace:\n\tOrdinal0 [0x00E07DF3+1474035]\n\tOrdinal0 [0x00D807D1+919505]\n\tOrdinal0 [0x00D1CB43+510787]\n\tOrdinal0 [0x00CCDB60+187232]\n\tOrdinal0 [0x00CCD9B5+186805]\n\tOrdinal0 [0x00CA1BAB+7083]\n\tOrdinal0 [0x00CA2126+8486]\n\tOrdinal0 [0x00CA2F00+12032]\n\tGetHandleVerifier [0x00F6231C+1249612]\n\tGetHandleVerifier [0x00EB1575+525221]\n\tGetHandleVerifier [0x00EB1310+524608]\n\tOrdinal0 [0x00E15D28+1531176]\n\tGetHandleVerifier [0x00EB1D4A+527226]\n\tOrdinal0 [0x00D975F6+1013238]\n\tOrdinal0 [0x00D9746F+1012847]\n\tOrdinal0 [0x00CA1A16+6678]\n\tOrdinal0 [0x00CA174A+5962]\n\tGetHandleVerifier [0x0120992C+4032348]\n\tBaseThreadInitThunk [0x774438F4+36]\n\tRtlUnicodeStringToInteger [0x77B35E13+595]\n\tRtlUnicodeStringToInteger [0x77B35DDE+542]\n\", \"message\": \"invalid argument: missing command parameters\", \"error\": \"invalid argument\"}}","errorStatus":-1,"error":"An unknown error has occurred.","httpStatusCode":400}
Below is the page object:
module.exports = {
url: function () {
return this.api.launchUrl
},
elements: {
app: { selector: 'div[id="app"]' },
login_usernameInput: { selector: 'input[id="user_id"]' },
login_passwordInput: { selector: 'input[id="password"]' },
login_submitButton: { selector: 'button[id="submit"]' }
},
commands: [
{
login () {
return this
.waitForElementPresent('span[id=welcomeToMyApp]')
.setValue('#login_usernameInput', process.env.APP_USERNAME)
.setValue('#login_passwordInput', process.env.APP_PASSWORD)
.click('#login_submitButton')
.waitForElementPresent('#app')
}
}
]
}
Test code:
module.exports = {
beforeEach: (browser, done) => {
browser.page.loginPage()
.navigate()
.login()
done()
},
'Test - DQM Page': function (browser) {
const dqmPage = browser.page.dqmPage()
dqmPage
.navigate()
.waitForElementVisible('body')
.click('#nextCountryTab')
.assert.visible('#nextCountry')
.end()
},
afterEach: (browser, done) => {
browser.custom().end()
setTimeout(function () {
done()
}, 200)
}
}
All the other steps, before click() in the login() method works perfectly fine. Even the setValue() functions are executed pretty well.
Please note, the submit button is pretty much visible and clickable.
I fixed this by specifying to use the previous version of Chrome (which right now is 74).
"desiredCapabilities": {
... clipped out my other capabilities for brevity ...
"version": "latest-1"
}
I then changed it to specifically say version 74. Both of these work but I don't want Chrome to upgrade to 76 and then tests start failing again if we haven't finished adopting whatever the real fix is.
"desiredCapabilities": {
... again - clipped for brevity ...
"browserName": "chrome",
"version": "74.0"
}
What SauceLabs says should work is the following. It doesn't work for me. I got this from their blog post at https://wiki.saucelabs.com/pages/viewpage.action?pageId=88801611
"desiredCapabilities": {
... clipped other configs again ...
"goog:chromeOptions": {"w3c": false}
}
I was able to fix this issue by updating to the newest version of Nightwatch. But the update broke other things. Here is some documentation on what might break after the update.
https://github.com/nightwatchjs/nightwatch/wiki/Migrating-to-Nightwatch-1.0

SyntaxError: Unexpected token { in Gruntfile.js

I don't manage to configure grunt. I have followed all the steps from Magento2 but I receive this syntax error.
grunt
Loading "Gruntfile.js" tasks...ERROR
>> SyntaxError: Unexpected token {
Warning: Task "default" not found. Use --force to continue.
Aborted due to warnings.
I have reinstalled both the grunt and the node.js, but it doesn't work.
Has anybody had the same problem?
Below you can see the Gruntfile.js ( that is original) posted.
Is it an error of this file or is there another problem?
Gruntfile.js
module.exports = function (grunt) {
'use strict';
var _ = require('underscore'),
path = require('path'),
filesRouter = require('./dev/tools/grunt/tools/files-router'),
configDir = './dev/tools/grunt/configs',
tasks = grunt.file.expand('./dev/tools/grunt/tasks/*'),
themes;
filesRouter.set('themes', 'dev/tools/grunt/configs/themes');
themes = filesRouter.get('themes');
tasks = _.map(tasks, function(task){ return task.replace('.js', '') });
tasks.push('time-grunt');
tasks.forEach(function (task) {
require(task)(grunt);
});
require('load-grunt-config')(grunt, {
configPath: path.join(__dirname, configDir),
init: true,
jitGrunt: {
staticMappings: {
usebanner: 'grunt-banner'
}
}
});
_.each({
/**
* Assembling tasks.
* ToDo: define default tasks.
*/
default: function () {
grunt.log.subhead('I\'m default task and at the moment I\'m empty, sorry :/');
},
/**
* Production preparation task.
*/
prod: function (component) {
var tasks = [
'less',
'autoprefixer',
'cssmin',
'usebanner'
].map(function(task){
return task + ':' + component;
});
if (typeof component === 'undefined') {
grunt.log.subhead('Tip: Please make sure that u specify prod subtask. By default prod task do nothing');
} else {
grunt.task.run(tasks);
}
},
/**
* Refresh themes.
*/
refresh: function () {
var tasks = [
'clean',
'exec:all'
];
_.each(themes, function(theme, name) {
tasks.push('less:' + name);
});
grunt.task.run(tasks);
},
/**
* Documentation
*/
documentation: [
'replace:documentation',
'less:documentation',
'styledocco:documentation',
'usebanner:documentationCss',
'usebanner:documentationLess',
'usebanner:documentationHtml',
'clean:var',
'clean:pub'
],
'legacy-build': [
'mage-minify:legacy'
],
spec: function (theme) {
var runner = require('./dev/tests/js/jasmine/spec_runner');
runner.init(grunt, { theme: theme });
grunt.task.run(runner.getTasks());
}
}, function (task, name) {
grunt.registerTask(name, task);
});
};
Thanks in advance!
I was getting the same error.
I installed node using the following commands and error resolved.
curl -sL https://deb.nodesource.com/setup_8.x | sudo bash -
sudo apt install nodejs
node -v
npm -v
Hope this helps!

e2e browser opens and close immedietly

I am trying to test my app and followed this link http://lathonez.github.io/2016/ionic-2-e2e-testing/ i merged my app with firebase. Everything worked good, but when i run npm run e2e browser opens and close immediately in my terminal pops an error.
I followed this link http://lathonez.github.io/2016/ionic-2-e2e-testing/
Actually my issue is that i could not able to see any action takes place in my e2e browser could some on help me
protractorconfig.js
exports.config = {
baseUrl: 'http://192.168.1.2:8100/',
specs: [
'../app/pages/home/home.e2e.ts',
'../app/pages/Admin/admin.e2e.ts',
//'../app/pages/Listing/lisitngPage.e2e.ts'
],
exclude: [],
framework: 'jasmine2',
allScriptsTimeout: 110000,
jasmineNodeOpts: {
showTiming: true,
showColors: true,
isVerbose: false,
includeStackTrace: false,
defaultTimeoutInterval: 400000
},
directConnect: true,
chromeOnly: true,
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
'args': ['--disable-web-security']
}
},
onPrepare: function() {
var SpecReporter = require('jasmine-spec-reporter');
jasmine.getEnv().addReporter(new SpecReporter({displayStacktrace: true}));
browser.ignoreSynchronization = false;
},
useAllAngular2AppRoots: true
};
gulpfile.ts
import { join } from 'path';
const config: any = {
gulp: require('gulp'),
appDir: 'app',
testDir: 'test',
testDest: 'www/build/test',
typingsDir: 'typings',
};
const imports: any = {
gulp: require('gulp'),
runSequence: require('run-sequence'),
ionicGulpfile: require(join(process.cwd(), 'gulpfile.js')),
};
const gulp: any = imports.gulp;
const runSequence: any = imports.runSequence;
// just a hook into ionic's build
gulp.task('build-app', (done: Function) => {
runSequence(
'build',
(<any>done)
);
});
// compile E2E typescript into individual files, project directoy structure is replicated under www/build/test
gulp.task('build-e2e', ['clean-test'], () => {
let typescript: any = require('gulp-typescript');
let tsProject: any = typescript.createProject('tsconfig.json');
let src: Array<any> = [
join(config.typingsDir, '/index.d.ts'),
join(config.appDir, '**/*e2e.ts'),
];
let result: any = gulp.src(src)
.pipe(typescript(tsProject));
return result.js
.pipe(gulp.dest(config.testDest));
});
// delete everything used in our test cycle here
gulp.task('clean-test', () => {
let del: any = require('del');
// You can use multiple globbing patterns as you would with `gulp.src`
return del([config.testDest]).then((paths: Array<any>) => {
console.log('Deleted', paths && paths.join(', ') || '-');
});
});
// run jasmine unit tests using karma with PhantomJS2 in single run mode
gulp.task('karma', (done: Function) => {
let karma: any = require('karma');
let karmaOpts: {} = {
configFile: join(process.cwd(), config.testDir, 'karma.config.js'),
singleRun: true,
};
new karma.Server(karmaOpts, done).start();
});
// run jasmine unit tests using karma with Chrome, Karma will be left open in Chrome for debug
gulp.task('karma-debug', (done: Function) => {
let karma: any = require('karma');
let karmaOpts: {} = {
configFile: join(process.cwd(), config.testDir, 'karma.config.js'),
singleRun: false,
browsers: ['Chrome'],
reporters: ['mocha'],
};
new karma.Server(karmaOpts, done).start();
});
// run tslint against all typescript
gulp.task('lint', () => {
let tslint: any = require('gulp-tslint');
return gulp.src(join(config.appDir, '**/*.ts'))
.pipe(tslint())
.pipe(tslint.report('verbose'));
});
// build unit tests, run unit tests, remap and report coverage
gulp.task('unit-test', (done: Function) => {
runSequence(
['lint', 'html'],
'karma',
(<any>done)
);
});

Resources