Getting error in setting up log4js-protractor-appender in protractor - protractor

My Conf.js looks like below:
// An example configuration file.
exports.config = {
directConnect: true,
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome'
},
// Framework to use. Jasmine is recommended.
framework: 'jasmine',
// Spec patterns are relative to the current working directory when
// protractor is called.
specs: ['test_spec1.js'],
// Options to be passed to Jasmine.
jasmineNodeOpts: {
defaultTimeoutInterval: 30000
},
var log4js = require('log4js');
beforeLaunch:function(){
if (fs.existsSync('./logs/ExecutionLog.log')) {
fs.unlink('./logs/ExecutionLog.log')
}
log4js.configure({
appenders: [
{ type: 'log4js-protractor-appender', category: 'protractorLog4js' },
{
type: "file",
filename: './logs/ExecutionLog.log',
category: 'protractorLog4js'
}
]
});
},
onPrepare: function() {
browser.logger = log4js.getLogger('protractorLog4js');
require('jasmine-reporters');
jasmine.getEnv().addReporter(
new jasmineReporters.JUnitXmlReporter('./Reports', true, true));
}
};
I get following error on running command "protractor conf.js"

You need to move the var log4js = require('log4js'); line to the top of the conf file, above the exports.config ={ .. } block. Also use const instead of var

Related

TypeError: protractorImageComparison is not a constructor

I try to run comparison tests and get Error: TypeError: protractorImageComparison is not a constructor. please advice
The same code worked in the full angular project but i needed to sperated the testing from the code.
i added my conf.file and the spec file
//protractor.conf.js:
const { SpecReporter } = require('jasmine-spec-reporter').SpecReporter;
exports.config = {
allScriptsTimeout: 15000,
specs: [
'src/tests/*.e2e-spec.js'
],
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
'args': ['no-sandbox']
}
},
directConnect: true,
baseUrl: 'https://localhost:4200/',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
onPrepare: function() {
require('ts-node').register({
project: require('path').join(__dirname, './tsconfig.json')
});
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
const protractorImageComparison =require('protractor-image-comparison');
browser.driver.manage().window().setSize(1366, 768);
browser.protractorImageComparison = new protractorImageComparison({
baselineFolder: '.\\e2e\\src\\screenshots\\baseline',
screenshotPath: '.\\e2e\\src\\screenshots\\actual_screenshots',
autoSaveBaseline: true
});
},
};
//test
import {browser } from 'protractor';
import {LoginPage} from '../pages/login.po';
describe('login page', function() {
beforeEach(function()
{
LoginPage.navigateTo();
});
it('login page should match the design', () => {
expect(browser.protractorImageComparison.checkScreen('login_Page')).toEqual(0);
});
});
If you are using the latest protractor-image-comparison, it appears that it says you should use it as a plugin. The constructor itself has been moved to https://github.com/wswebcreation/protractor-image-comparison/blob/master/lib/index.ts#L9 and is not exported.
The plugin should be added in your Protractor config per the readme file:
plugins: [
{
// The module name
package: 'protractor-image-comparison',
// Some options, see the docs for more
options: {
baselineFolder: join(process.cwd(), './baseline/'),
formatImageName: `{tag}-{logName}-{width}x{height}`,
screenshotPath: join(process.cwd(), '.tmp/'),
savePerInstance: true,
// ... more options
},
},
],

Protractor: how to prevent chrome webdriver service from stopping session automatically

When my testcase is running, the session is automatically stopped after 10mins.
INFO [ActiveSessions$1.onStop] - Removing session fbd843ab66cb10a21d00b07eb4466970 (org.openqa.selenium.chrome.ChromeDriverService)
Is there any way to not stop automatically, or extend the time ? The conf.js file is as follows. Thanks.
// File: conf.js
exports.config = {
framework: 'jasmine',
seleniumAddress: 'http://localhost:4444/wd/hub',
// set default time out for pending asynchronous tasks in Angular application 60 mins
allScriptsTimeout: 3600000,
// Options to be passed to Jasmine-node.
jasmineNodeOpts: {
isVerbose: true,
// use colors in the command line report.
showColors: true,
// override jasmine.DEFAULT_TIMEOUT_INTERVAL for asynchronous callback
defaultTimeoutInterval: 3600000
},
onPrepare: () =>{
browser.ignoreSynchronization = false;
browser.driver.manage().window().maximize();
let origFn = browser.driver.controlFlow().execute;
// set protractor wait time
browser.driver.controlFlow().execute = function () {
let args = arguments;
// queue 100ms wait
origFn.call(browser.driver.controlFlow(), () => {
return protractor.promise.delayed(100);
});
return origFn.apply(browser.driver.controlFlow(), args);
};
},
capabilities: {
'browserName': 'chrome',
'platform': 'ANY',
'version': 'ANY',
'shardTestFiles': false,
'chromeOptions': {
args: ['--no-sandbox', '--test-type=browser', 'disable-infobars'],
prefs: {
'download': {
'prompt_for_download': false
}
}
}
},
// command line params
params: {
all: '',
},
// Specify the name of the specs files.
specs: ['./tests/link.js'],
// Run specified suites: protractor conf.js --suite portfolio
suites: {
all: 'tests/*'
}
}

Gerkin and Cucumber in Angular 5: Undefined

When I try to create a test using Cucumber and Gherkin I get a strange error. I show you the error first, then the files login.step.ts and login.po.ts:
// Error:
Undefined. Implement with the following snippet:
When('Enter the card number in the box', function () {
// Write code here that turns the phrase above into concrete actions
return 'pending';
});
// login.step.ts
import { expect } from 'chai';
const { Given, When, Then, Before } = require('cucumber');
import { browser, by, element } from 'protractor';
import { LoginPage } from './login.po';
let login: LoginPage;
Before(() => {
login = new LoginPage();
});
Given(/^Entering in Login$/, { timeout: 10 * 5000 }, async () => {
await browser.get('http://localhost:49152/login');
});
When(/^Enter the card number in the box$/, () => {
// login.setCardNumber('1234').then((txt) => {
// return 'ready!?';
// })
login.setCardNumber('1234');
});
// login.po.ts
import { browser, by, element, until } from 'protractor';
export class LoginPage {
navigateTo() {
return browser.get('/login');
}
setCardNumber(cardNumber) {
const input = element(by.css('#box'));
return input.sendKeys(cardNumber);
}
}
The first test passes successfully, but in the second test, the process ends in error.
[EDIT]
Adding the protractor.conf.js file:
exports.config = {
allScriptsTimeout: 11000,
specs: [
// './e2e/**/*.e2e-spec.ts',
'./e2e/features/*.feature'
],
capabilities: {
'browserName': 'chrome',
chromeOptions: {
args: ['disable-infobars']
},
metadata: {
browser: {
name: 'chrome',
version: '58'
},
device: 'Xubuntu Linux',
platform: {
name: 'Linux',
version: '16.04'
}
}
},
directConnect: true,
frameworkPath: require.resolve('protractor-cucumber-framework'),
plugins: [{
package: 'protractor-multiple-cucumber-html-reporter-plugin',
options: {
automaticallyGenerateReport: true,
removeExistingJsonReportFile: true
}
}],
cucumberOpts: {
require: ['./e2e/steps/**/*.ts', './e2e/support/*.ts'],
tags: [],
dryRun: false,
compiler: [],
format: 'json:reports/results.json',
strict: true
},
baseUrl: 'http://localhost:4200/',
SELENIUM_PROMISE_MANAGER: false,
framework: 'custom',
onPrepare() {
require('ts-node').register({
project: 'e2e/tsconfig.e2e.json'
});
}
};
remove the double quote " behind box in /^Enter the card number in the box"$/
I found the answer to my problem. I only had to include the following configuration line to my Before() step in my test:
browser.ignoreSynchronization = true;
According to what I read in different places, it seems that Chrome is looking to perform some task with sockets, and with this line we are disabling this task.

Unable to take test report from multiple browsers at a time using protractor

I am unable to take Test report for Multiple browsers at a time using protractor.
I tried below code
var Jasmine2HtmlReporter = require('C:/Users/agudla/AppData/Roaming/npm/node_modules/protractor-jasmine2-html-reporter');
exports.config = {
allScriptsTimeout: 11000,
seleniumAddress : 'http://localhost:4444/wd/hub',
multiCapabilities : [
{'browserName' : 'firefox'},
{'browserName' : 'chrome'}
],
suites : {
jobs : [
'e2e/Jobs/Manage Jobs/ApplyJobs/ApplyJobs.e2e-spec.ts',]
},
baseUrl : 'http://localhost:4200/',
framework : 'jasmine2',
jasmineNodeOpts : {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
onPrepare() {
//jasmine.getEnv().addReporter(reporter);
browser.getProcessedConfig().then(function(config){
var capabilities = config.capabilities;
jasmine.getEnv().addReporter(
new Jasmine2HtmlReporter({
savePath : '',
fileName : 'protractor-report-'+capabilities.platform+'-'+capabilities.browserName,
takeScreenshotOnlyOnFailure : true
})
);
});
require('ts-node').register({
project: 'e2e/tsconfig.e2e.json'
});
},
I run "selenium webdriver server" from the command prompt and run the test scripts . The Jasmine html report is always displaying the latest browser result , in this case it is always displaying "firefox" browser related test report.
I want to take test report from both "chrome and fire fox" browsers at a time. Can any one suggest me how to do this?
Use below code for multi-capability reporting. you can refer my repo on github for more details.
Click here
var Jasmine2HtmlReporter = require('protractor-jasmine2-html-reporter');
var log4js = require('log4js');
var params = process.argv;
var args = process.argv.slice(3);
exports.config = {
//seleniumServerJar: './node_modules/gulp-protractor/node_modules/protractor/selenium/selenium-server-standalone-2.48.2.jar',
seleniumAddress: 'http://localhost:4444/wd/hub',
allScriptsTimeout: 10000,
framework: 'jasmine2',
onPrepare: function () {
return new Promise(function(fulfill, reject) {
browser.getCapabilities().then(function(value) {
reportName = 'protractor-report-' + '_' + value.get('browserName') + '_' + Math.floor(Math.random()*1E16);
jasmine.getEnv().addReporter(
new Jasmine2HtmlReporter({
savePath: __dirname+'/target',
docTitle: 'Web UI Test Report',
screenshotsFolder: '/image',
//takeScreenshots: true,
takeScreenshotsOnlyOnFailures: true,
consolidate: true,
consolidateAll: true,
preserveDirectory: true,
//cleanDirectory: false,
//fixedScreenshotName: true,
fileName: "my-report.html",
fileNamePrefix: reportName
})
);
fulfill();
});
});
},
afterLaunch: function afterLaunch() {
var fs = require('fs');
var output = '';
fs.readdirSync('target/').forEach(function (file) {
if (!(fs.lstatSync('target/' + file).isDirectory()))
output = output + fs.readFileSync('target/' + file);
});
fs.writeFileSync('target/ConsolidatedReport.html', output, 'utf8');
},
suites:{
example:['./test/e2e/specs/**/*Spec.js',]
},
multiCapabilities: [
{
'browserName': 'chrome'
},
{
'browserName': 'firefox'
}
],
// Options to be passed to Jasmine-node.
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 200000
}
};

Karma debugging in Chrome no longer working

We are working on an Angular project where we are using Karma/Jasmine for our testing environment. We've been using the karma-chrome-launcher for debugging the tests and it was working great. For some reason, it has stopped working lately. I can't figure out why though, as we haven't changed anything regarding that pipeline. We tried updating to latest Karma (1.4.1), but that didn't help. Has anyone else seen this issue and been able to fix it? Help is appreciated. I've attached two images of what the Chrome inspector looks like when you first open the debugger and then after setting a breakpoint and hitting Refresh (it should look the same as the 1st image, but doesn't) edit: karma.config at bottom as well
'use strict';
var path = require('path');
var conf = require('./gulp/conf');
var _ = require('lodash');
var wiredep = require('wiredep');
var pathSrcHtml = [
path.join(conf.paths.src, '/**/*.html')
];
function listFiles() {
var wiredepOptions = _.extend({}, conf.wiredep, {
dependencies: true,
devDependencies: true
});
var patterns = wiredep(wiredepOptions).js
.concat([
path.join(conf.paths.src, '/app/**/*.module.js'),
path.join(conf.paths.src, '/app/**/*.js')
])
.concat(pathSrcHtml)
.concat('karmaMobileFramework/*.js');
var files = patterns.map(function(pattern) {
return {
pattern: pattern
};
});
files.push({
pattern: path.join(conf.paths.src, '/assets/**/*'),
included: false,
served: true,
watched: false
});
return files;
}
module.exports = function(config) {
var configuration = {
files: listFiles(),
singleRun: false,
autoWatch: true,
preprocessors : {
'/**/*.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
stripPrefix: conf.paths.src + '/',
moduleName: 'directive-templates'
},
logLevel: 'WARN',
frameworks: ['jasmine', 'jasmine-matchers', 'angular-filesort'],
angularFilesort: {
whitelist: [path.join(conf.paths.src, '/**/!(*.html|*.spec|*.mock).js')]
},
browsers : ['Chrome'],
plugins : [
'karma-chrome-launcher',
'karma-angular-filesort',
'karma-coverage',
'karma-jasmine',
'karma-jasmine-matchers',
'karma-ng-html2js-preprocessor',
'karma-htmlfile-reporter',
'karma-junit-reporter'
],
coverageReporter: {
type : 'html',
dir : 'reports/coverage/',
reporters: [
{ type: 'html', subdir: 'report-html' },
{ type: 'cobertura', subdir: 'report-jenkins' }
]
},
reporters: ['progress', 'html', 'junit'],
junitReporter: {
outputDir: 'reports/tests/',
outputFile: 'test-results.xml',
useBrowserName: false
},
htmlReporter: {
outputFile: 'reports/tests/results.html',
pageTitle: 'BOLT Unit Tests'
},
proxies: {
'/assets/': path.join('/base/', conf.paths.src, '/assets/')
}
};
// This is the default preprocessors configuration for a usage with Karma cli
// The coverage preprocessor is added in gulp/unit-test.js only for single tests
// It was not possible to do it there because karma doesn't let us now if we are
// running a single test or not
configuration.preprocessors = {};
pathSrcHtml.forEach(function(path) {
configuration.preprocessors[path] = ['ng-html2js'];
});
config.set(configuration);
};