Protractor-Jasmine2-HTML-Report - protractor

I am working on report execution part in Protractor and using Jasmine2 Html Reporter. I am able to generate a report but when my test passes completely without any failure still report shows status as 0.00%. I am not sure why this is happening. I am also attaching the snap shot for the reference.
The code is :
var HtmlReporter = require('protractor-jasmine2-html-reporter');
var reporter = new HtmlReporter({
plugins: [{
package: 'jasmine2-protractor-utils',
showSummary: true,
reportTitle: "Clinicare Report",
filename: 'Clinicarereport.html',
disableHTMLReport: false,//disableHTMLReport
disableScreenshot: false,
captureOnlyFailedSpecs: true,
screenshotPath:'./reports/screenshots',
screenshotOnExpectFailure:true,
screenshotOnSpecFailure:true,
dest: 'protractor-reports',
filename: 'protractor-report.html',
takeScreenshots: true,
ignoreSkippedSpecs: true,
takeScreenshotsOnlyOnFailures: true
// screenshotsFolder: 'F:\\Screeshots'
}]
});
exports.config =
{
directconnect: true,
capabilities: {'browserName': 'chrome'},
framework: 'jasmine',
specs: ['example1.js'],
jasmineNodeOpts: {
defaultTimeoutInterval: 300000
},
onPrepare: function() {
// Add a screenshot reporter and store screenshots to `/tmp/screenshots`:
jasmine.getEnv().addReporter(reporter);
}
}
The spec code is:
var Excel = require('exceljs');
var XLSX = require('xlsx');
var os = require('os');
var TEMP_DIR = os.tmpdir();
var wrkbook = new Excel.Workbook();
describe('Open the clinicare website by logging into the site', function () {
it('Should Add a text in username and password fields and hit login button', function () {
console.log("hello6");
var wb = XLSX.readFile('E:\\Demo\\Generate a test report\\Data_Login.xlsx');
var ws = wb.Sheets.Sheet1;
var json = XLSX.utils.sheet_to_json(wb.Sheets.Sheet1);
console.log("json", json);
//var json = XLSX.utils.sheet_to_json(wb.Sheets.Sheet1);
//console.log("json", json);
for(var a = 0; a < json.length ; a++){
console.log("Test_URL", json[a].Test_URL);
console.log("User_Name", json[a].User_Name);
console.log("Password", json[a].Password);
browser.get(json[a].Test_URL);
//Perform Login:UserName
element(by.model('accessCode')).sendKeys(json[a].User_Name);
//Perform Login:Password
element(by.model('password')).sendKeys(json[a].Password);
//Perform Login:LoginButton
element(by.css('.btn.btn-primary.pull-right')).click();
//Clicking on New Tab
element(by.xpath('/html/body/div[3]/div[1]/div[17]/div/div/table[2]/thead/tr/th[1]/i')).click();
//Clicking on Image for Logout
element(by.css('.user-auth-img.img-circle')).click();
browser.driver.sleep(2000)
//Clicking on LogOut Button
element(by.xpath('/html/body/div[3]/div[1]/div[16]/div[1]/div/div[2]/nav/div[2]/ul/li[4]/ul/li[5]/a/span')).click();
browser.driver.sleep(2000)
//Clicking on Ok for confirmation
element(by.id('logout')).click();
console.log(json[a].User_Name + "Passed the Test");
};
})
});

Try with below spec file it's working fine.
Results you can see
describe("basic test", function () {
beforeAll(function () {
console.log('beforeAll');
});
beforeEach(function () {
console.log('beforeEach');
});
afterAll(function () {
console.log('afterAll');
});
afterEach(function () {
console.log('afterEach');
});
it("Test Case 1: to verify see the global functions hierarchy", function () {
console.log('Sample Test 1');
});
it("Test Case 2: to verify see the global functions hierarchy", function () {
browser.get('http://www.angularjs.org');
element(by.model('todoText')).sendKeys('write a protractor test');
element(by.css('[value="add"]')).click();
var todoList = element.all(by.repeater('todo in todos'));
expect(todoList.count()).toEqual(3);
});
it('should greet the named user', function() {
browser.get('http://www.angularjs.org');
element(by.model('yourName')).sendKeys('Julie');
var greeting = element(by.binding('yourName'));
expect(greeting.getText()).toEqual('Hello Julie!');
});
});

Related

protractor is not capturing the Screenshot with Cucumber Reporter

i am using Protractor with Cucumber to test angular application, for reporting i am using "cucumber-html-reporter", i am not able to capture the screenshot in report and its not getting saved in the given folder as well
reporter.js
const reporter = require("cucumber-html-reporter");
cucumberReporteroptions = {
theme: "bootstrap",
//jsonFile: targetJson,
jsonDir: targetjsonDir,
output: htmlReports + "/cucumber_reporter"+datetime+".html",
reportSuiteAsScenarios: true,
storeScreenshots:true,
screenshotsDirectory:htmlReports +'/screenshots',
reportSuiteAsScenarios:true,
launchReport:true,
ignoreBadJsonFile:true
};
class Reporter {
static createHTMLReport() {
try {
reporter.generate(cucumberReporteroptions); //invoke cucumber-html-reporter
} catch (err) {
if (err) {
console.log("Failed to save cucumber test results to json file.");
console.log(err);
}
}
}
hooks.js
After(function(scenario) {
const attach = this.attach;
return browser.takeScreenshot().then(function(png) {
const decodedImage = new Buffer(png, "base64");
return attach(decodedImage, "image/png");
});
});
Quick checks that you can do from your side, to make sure reporter is invoked properly:
onPrepare: () => {
browser.ignoreSynchronization = true;
browser.manage().window().maximize();
Reporter.createDirectory(jsonReports);
},
cucumberOpts: {
compiler: "ts:ts-node/register",
format: "json:./reports/json/cucumber_report.json",
require: ["../../typeScript/stepdefinitions/*.js", "../../typeScript/support/*.js"],
strict: true,
},
onComplete: () => {
Reporter.createHTMLReport();
},
Can you try this,
defineSupportCode(({After}) => {
After(function(scenario) {
if (scenario.isFailed()) {
var attach = this.attach;
return browser.takeScreenshot().then(function(png) {
var decodedImage = new Buffer(png, "base64");
return attach(decodedImage, "image/png");
});
}
});
});
Lemme know how it goes!

Test Report is not generating using 'protractor-angular-screenshot-reporter'

I am using POM concepts and all the instructions given :
https://npm.runkit.com/protractor-angular-screenshot-reporter
https://github.com/bcole/protractor-angular-screenshot-reporter/blob/master/README.md
but still no reports is generating. Is that anything I am lacking. Earlier I have used 'protractor-jasmine2-html-reporter' and it was working fine.
Console output I am getting is correct on running protractor conf.js using cmd:
4 specs, 3 failures
Finished in 32.847 seconds
[11:32:40] I/local - Shutting down selenium standalone server.
[11:32:40] I/launcher - 0 instance(s) of WebDriver still running
[11:32:40] I/launcher - chrome #01 failed 3 test(s)
[11:32:40] I/launcher - overall: 3 failed spec(s)
[11:32:40] E/launcher - Process exited with error code 1
Project Structure:
Project Structure
pages/AllevaHome.js
var AllevaHomePage = function() {
var logoutBtn = element(by.className('logoutbtn'));
this.isLogoutDisplays = function(){
var flag = logoutBtn.isDisplayed();
return flag
};
this.logout = function(){
logoutBtn.click();
};
};
module.exports = new AllevaHomePage();
pages/AllevaLogin.js
var AllevaLoginPage = function() {
var username = element(by.model('LoginViewModel.UserName'));<br>
var password = element(by.model('LoginViewModel.Password'));<br>
var loginBtn = element(by.className('orange-btn login_btn'));<br>
var securityAns = element(by.model('twoFactorModel.answer'));<br>
var proceedBtn = element(by.css('[value="Proceed"]'));<br>
this.get = function() {
browser.get('some url');
browser.manage().window().maximize();
};
function setUsername(user){
username.sendKeys(user);
};
function setPassword(pass){
password.sendKeys(pass);
};
function setAnswer(ans){
securityAns.sendKeys(ans);
};
this.login = function(user, pass, ans){
setUsername(user);
setPassword(pass);
loginBtn.click();
setAnswer(ans);
proceedBtn.click();
};
/* this.getGreetingText = function() {
return greeting.getText();
};*/
};
module.exports = new AllevaLoginPage();
testdata/LoginData.js
'use strict';
module.exports = {
LoginData: {
'Valid Username/Password': {username: 'someuser', password: 'somepass',
answer: 'someans'},
'Invalid Username/Correct Password': {username: 'testuser', password:
'Test#12345', answer: 'kusum'},
'Invalid Username/Invalid Password': {username: 'testuser', password:
'Test#1234', answer: 'kusum'},
'Valid Username/Invalid Password': {username: 'rohitnegi', password:
'Test#1234', answer: 'kusum'}
}
}
tests/AllevaLoginTest.js
var AllevaLoginObj = require('../pages/AllevaLogin.js');
var AllevaHomeObj = require('../pages/AllevaHome.js');
var LoginData = require('../testdata/LoginData.js');
var using = require('jasmine-data-provider');
describe('Checking Alleva Login Functionality', function() {
using(LoginData.LoginData, function(data, description) {
it('Login with: '+description, function() {
AllevaLoginObj.get();
AllevaLoginObj.login(data.username, data.password, data.answer);
expect(AllevaHomeObj.isLogoutDisplays());
})
});
afterEach(function() {
AllevaHomeObj.logout();
})
});
Conf.js:
var HtmlReporter = require('protractor-angular-screenshot-reporter');
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: [
'./tests/AllevaLoginTest.js'
],
capabilities: {
'browserName': 'chrome'
},
onPrepare: function() {
jasmine.getEnv().addReporter(new HtmlReporter({
baseDirectory: '/tmp/screenshots'
}).getJasmine2Reporter());
},
jasmineNodeOpts: {
onComplete: null,
isVerbose: true,
showColors: true,
includeStackTrace: true,
defaultTimeoutInterval: 2500000
}
};
Please let me know if you need anything else.

shardTestFiles not working with gulp

I am using gulp wrapper for protractor for my tests. ShardTestFiles option specified below in my main protractor protractor file (under multicapabilities) is not working. My browser is still running as only 1 instance and my tests are still taking same amount of time.
I am using protractor version 4.0.9.
Below is how my conf file inside project folder is set-up.
var ProtractorConfig = require('../../ProtractorConfig');
exports.config = new ProtractorConfig({
suites: {test: ['./spec/**/censusCat*.spec.js']},
siteName: '',
isAngular: true,
params: require('./params'),
allScriptsTimeout: 25000,
jasmineNodeOpts: {
defaultTimeoutInterval: 500000,
}
});
This is how my main protractor file is set-up:
'use strict';
require('dotenv').load();
var _ = require('lodash');
var path = require('path');
function ProtractorConfig(options, isMobile) {
// Protractor options
this.seleniumAddress = process.env.SELENIUM_ADDRESS;
this.multiCapabilities = [{
browserName: 'chrome',
maxInstances : 2,
shardTestFiles: true,
}];
this.framework = 'jasmine2';
this.params = require('./params');
this.jasmineNodeOpts = {print: function() {}};
this.plugins = [{path: '../../plugins/protractor-extensions/index.js'}];
this.onPrepare = function() {
var siteName = this.siteName || '';
var isAngular = this.isAngular;
if (isAngular) {
browser.ignoreSynchronization = false;
} else {
browser.ignoreSynchronization = true;
}
browser.resize(1280, 1040);
// Set up globally available objects
global._ = _;
global.params = browser.params;
global.EC = protractor.ExpectedConditions;
browser.params.baseUrl = '';
}.bind(this);
_.merge(this, options);
}
module.exports = ProtractorConfig;
Below is how my gulp file is structured:
var env = require('envalid');
var gulp = require('gulp');
var path = require('path');
var util = require('gulp-util');
var simpleCommand = require('simple-command');
var binPath = './node_modules/.bin/';
gulp.task('test', function(cb) {
testSite('sites/' + util.env.site, cb);
});
gulp.task('default', ['test']);
function runModule(name, params, cb) {
new simpleCommand(path.join(binPath, name), params, process.cwd()).run(cb);
}
function runProtractor(params, cb) {
runModule('protractor', params, cb);
}
function testSite(site, cb) {
var params = [
site + '/protractor.conf.js','--suite=test', '--params.siteName=registry.ngccoin.com'
];
runProtractor(params, function(err) {
cb();
});
}
Can someone please suggest why my shardTestFiles option is not working?

When I isolate a test it passes, but when run sequentially with other tests it fails with NoSuchElementError

I was making some changes to the page objects we use for running our Protractor tests to run on Sauce Labs i.e., calling a utility method to get browser and platform so we can use the appropriate test user, and after making the change I kept getting a NoSuchElementError when running the test suite.
When I isolate the logout test, it passes, but when run in conjunction with any other files, it fails. Currently, I'm only running the login test and logout test on Chrome to limit the possible causes.
We use page objects to navigate to a testable state, in this case a login page object and a dashboard page object (logging in takes you to the dashboard).
The login page object:
'use strict';
var TestUtils = require('../../util/test-utils.js');
var HeaderPageElement = require('../page_elements/header-page-element.js');
var LoginPage = function () {
var self = this;
this.get = function () {
browser.get('http://localhost:9000/index.html');
this.header = new HeaderPageElement();
this.loginForm = element(by.name('loginForm'));
this.usernameInput = element(by.model('credentials.username'));
this.passwordInput = element(by.model('credentials.password'));
this.loginButton = element(by.name('loginButton'));
this.signupLink = element(by.xpath('//a[#ui-sref="signup"]'));
};
this.setCredentials = function (username, password) {
var deferred = protractor.promise.defer();
var testUtils = new TestUtils();
testUtils.getCapabilities().then(function (capabilities) {
return testUtils.getTestUser(capabilities.browserName, capabilities.platform);
}).then(function (testUser) {
username = username || testUser.username;
password = password || testUser.password;
self.usernameInput.sendKeys(username);
self.passwordInput.sendKeys(password);
deferred.fulfill();
});
return deferred.promise;
};
this.login = function (username, password) {
return this.setCredentials(username, password).then(function () {
return self.loginButton.click();
});
};
this.signup = function () {
return this.signupLink.click();
};
this.get();
};
module.exports = LoginPage;
The dashboard page object:
'use strict';
var LoginPage = require('./login-page.js');
var HeaderPageElement = require('../page_elements/header-page-element.js');
var ProjectCreateModalPageElement = require('../page_elements/project-create-modal-page-element.js');
var DashboardPage = function () {
var self = this;
this.get = function () {
var loginPage = new LoginPage();
loginPage.login();
this.header = new HeaderPageElement();
this.newProjectButton = element(by.name('newProjectButton'));
this.projectFilterInput = element(by.name('projectFilterInput'));
};
this.createNewProject = function (projectTitle, projectTypes) {
var deferred = protractor.promise.defer();
this.newProjectButton.click().then(function () {
var modalPage = new ProjectCreateModalPageElement();
modalPage.createNewProject(projectTitle, projectTypes);
deferred.fulfill();
});
return deferred.promise;
};
this.get();
};
module.exports = DashboardPage;
These are the tests that are being run.
The login test:
'use strict';
var LoginPage = require('./pages/login-page.js');
describe('login test', function () {
var page;
beforeEach(function () {
page = new LoginPage();
});
it('should be directed to login', function () {
expect(page.loginForm.isPresent()).toBe(true);
});
it('Login button should be disabled', function () {
expect(page.loginButton.getAttribute('disabled')).toEqual('true');
page.setCredentials('wrong', 'user').then(function () {
expect(page.loginButton.getAttribute('disabled')).toEqual(null);
});
});
it('login should fail and remain at login screen', function () {
page.login('wrong', 'user').then(function () {
expect(page.loginForm.isPresent()).toBe(true);
});
});
it('login success should redirect to dashboard', function () {
page.login().then(function () {
browser.wait(function () {
return $('#dashboard').isPresent();
});
expect($('#dashboard').isDisplayed()).toBe(true);
});
});
});
The logout test:
'use strict';
var DashboardPage = require('./pages/dashboard-page.js');
describe('logout test', function () {
var page;
beforeEach(function () {
page = new DashboardPage();
});
it('logout success should redirect to login page', function () {
page.header.logout().then(function() {
browser.wait(function () {
return $('#login').isPresent();
});
expect($('#login').isDisplayed()).toBe(true);
});
});
});
The error I get when running these tests sequentially is as follows:
NoSuchElementError: No element found using locator: by.model("credentials.username")
The line it specifies is the get method inside the DashboardPage object, whereby it instantiates a LoginPage object and calls the login method so as to navigate to the dashboard:
this.get = function () {
var loginPage = new LoginPage();
loginPage.login();
this.header = new HeaderPageElement();
this.newProjectButton = element(by.name('newProjectButton'));
this.projectFilterInput = element(by.name('projectFilterInput'));
};
For whatever reason, the usernameInput of the login page hasn't been set by the time the login method is called.
I'm quite sure it's got something to do with not having coded promises correctly, but I've been bashing my head against it for days without any success. Any help would be greatly appreciated.

protractor test timed out on Chrome but not on FF

I'm running a protractor test.
there is a login part which is not Angular and then the home page which is Angular part.
after passing the login part - on Chrome I get a Timeout, but on FF it continues successfully.
it used to run also on Chrome before, and a friend using Robot Framework doesn't get to timeout even when using chrome.
error message:
timeout: timed out after 30000 msec waiting for spec to complete
I've tries also adding
defaultTimeoutInterval: 360000
but it didn't help. it's just keep waiting.
config.js:
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
capabilities: {
'browserName': 'chrome'
// 'browserName': 'firefox'
},
specs: ['*/loginEAPTest.js'],
params: {
login: {
user: '****',
password: '****'
}
},
resultJsonOutputFile: 'TestResults/Test.js',
jasmineNodeOpts: {
isVerbose: true,
showColors: true,
//defaultTimeoutInterval: 360000,
includeStackTrace: true
},
onPrepare: function() {
// for non-angular page
browser.ignoreSynchronization = true;
}
};
loginEAPTest.js:
var LoginPage = require('../global/LoginPage');
var capture = require('../global/screenshots');
describe('login Testing', function () {
var login = new LoginPage();
beforeEach(function(){
login.get();
login.justClickLogin();
}
);
it('Should login using Email & Password', function () {
browser.sleep(10000);
browser.driver.findElement(by.id('userName_str')).sendKeys ("****");
browser.driver.findElement(by.id('password')).sendKeys("******");
browser.driver.findElement(by.xpath("//input[contains(#value,'Log In')]")).click();
browser.ignoreSynchronization = false;
browser.sleep(5000);
browser.switchTo().defaultContent();
expect(element(by.css('[data-ui-sref=myApps]')).isDisplayed()).toBe(true);
});
});
LoginPage.js (relevant part):
this.justClickLogin = function() {
var loginObj = this;
loginObj.signInButton.click().then(function () {
console.log("press login");
var loginframe = element(by.tagName('iframe'));
console.log("before switch");
browser.switchTo().frame(0);
console.log("after switch");
browser.sleep(4000);
});
};
thanks.