Error attempting to retrieve CODE sent to gmail account using MailListener Protractor/Jasmine end to end Test - email

I have already installed MailListener
npm install mail-listener2 --save-dev
In My Config.js file, I have
exports.config = {
directConnect: true,
capabilities: {
browserName: 'chrome',
},
framework: 'jasmine2',
onPrepare: function () {
var AllureReporter = require('jasmine-allure-reporter');
var AllureReporter = require('../index');
jasmine.getEnv().addReporter(new AllureReporter({
resultsDir: 'allure-results'
}));
// Mail Listener
var MailListener = require("mail-listener2");
// here goes your email connection configuration
var mailListener = new MailListener({
username: "myemail#gmail.com",
password: "mygmailpassword!",
host: "imap.gmail.com",
port: 993, // imap port
tls: true,
tlsOptions: { rejectUnauthorized: false },
mailbox: "INBOX", // mailbox to monitor
searchFilter: ["UNSEEN", "FLAGGED"], // the search filter being used after an IDLE notification has been retrieved
markSeen: true, // all fetched email willbe marked as seen and not fetched next time
fetchUnreadOnStart: true, // use it only if you want to get all unread email on lib start. Default is `false`,
mailParserOptions: { streamAttachments: true }, // options to be passed to mailParser lib.
attachments: true, // download attachments as they are encountered to the project directory
attachmentOptions: { directory: "attachments/" } // specify a download directory for attachments
});
mailListener.start();
mailListener.on("server:connected", function () {
console.log("... Mail listener initialized");
});
global.mailListener = mailListener;
},
onCleanUp: function () {
mailListener.stop();
},
// Spec patterns are relative to the current working directory when
// protractor is called.
specs: [
'../e2e/login_spec.js'
],
// Options to be passed to Jasmine.
jasmineNodeOpts: {
defaultTimeoutInterval: 30000
}
};
in my login_spec.js file i have the function
function getLastEmail() {
var deferred = protractor.promise.defer();
console.log("Waiting for an email...");
mailListener.on("mail", function(mail){
deferred.fulfill(mail);
});
return deferred.promise;
};
In the Same login_spec.js
i am trying
var loginData = require('../data.json');
var Login_Objects = require('../page_objects/login_objects');
describe('2Factor Login:', function () {
dataProvider(loginData, function (data) {
Login_Objects.EnterUserName(data.username)
Login_Objects.EnterUserName(data.password)
Login_Objects.ClickLogin()
//Code is sent to email
browser.controlFlow().wait(getLastEmail()).then(function (email){
var pattern = /Code for your transfer (\w+)/g;
var regCode = pattern.exec(email.text)[1];
console.log("Registration code : = "+regCode);
//Pass the code to my methods in the objects file.
//Login_Objects.Enter2FactorCode(regCode)
//Login_Objects.ClickVerify()
})
})
})
here my Login_Objects.Enter2FactorCode(regCode) method will just send keys to the 2factor webelement [but i am not yet at that stage]
At this point i am expecting the email to be printed by the function
console.log("Registration code : = "+regCode);
On the Console I am Getting the message :
... Mail listener initialized
NOTE: I have already allowed unsecure apps to access that gmail account
Findings:
I am getting an error
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
My reference is this >> Fetching values from email in protractor test case

Related

How to add custom logs in Protractor test reports

I'm trying to add some custom logs to my protractor test report. I've app log file in my project folder which has the logs captured using log4js. I want these log entries to be shown in my test report as well. Currently I'm using chercher report. Since I'm a beginner to protractor, I'm not sure how to do this. Can anybody help me on this? Thanks in advance!
spec.js
fdescribe('Protractor Perfecto Demo', function () {
it('should pass test', function () {
browser.reportingClient.stepStart('Step 1: Navigate Google');
browser.driver.get('https://www.google.com'); //Navigate to google.com
browser.reportingClient.stepEnd();
//Locate the search box element and insert text
//Click on search button
browser.reportingClient.stepStart('Step 2: Send Keys');
browser.driver.findElement(by.name('q')).sendKeys('PerfectoCode GitHub');
browser.reportingClient.stepEnd();
browser.reportingClient.stepStart('Step 3: Click');
browser.driver.findElement(by.css('#tsbb > div')).click();
browser.reportingClient.stepEnd();
});
//This test should fail
it('should fail test', function () {
browser.reportingClient.stepStart('Step 1: Navigate Google');
browser.driver.get('https://www.google.com'); //Navigate to google.com
browser.reportingClient.stepEnd();
//Locate the search box element and insert text
//Click on search button
browser.reportingClient.stepStart('Step 2: Send Keys');
browser.driver.findElement(by.name('q')).sendKeys('PerfectoCode GitHub');
browser.reportingClient.stepEnd();
browser.reportingClient.stepStart('Step 3: Click');
browser.driver.findElement(by.css('#tsbbbsdasd > div')).click();
browser.reportingClient.stepEnd();
});
afterAll(function(done){
process.nextTick(done);
});
});
conf.js
var reportingClient;
exports.config = {
//Remote address
// seleniumAddress: 'https://MY_HOST.perfectomobile.com/nexperience/perfectomobile/wd/hub',
directConnect: true,
//Capabilities to be passed to the webdriver instance.
capabilities: {
browserName: 'chrome'
// user: 'MY_USER',
// password: 'MY_PASS',
// platformName: 'Android',
//deviceName: '123456',
},
//Framework to use. Jasmine is recommended.
framework: 'jasmine',
// Spec patterns are relative to the current working directly when
// protractor is called.
specs: ['./tests/SignupAutomation_spec.js'],
// Options to be passed to Jasmine.
jasmineNodeOpts: {
showColors: true, // Use colors in the command line report.
defaultTimeoutInterval: 120000 // Time to wait in ms before a test fails. Default value = 30000
},
onComplete: function () {
// Output report URL
return reportingClient.getReportUrl().then(
function (url) {
console.log(`Report url = ${url}`);
}
);
},
onPrepare: function () {
const Reporting = require('perfecto-reporting');
reportingClient = new Reporting.Perfecto.PerfectoReportingClient(new Reporting.Perfecto.PerfectoExecutionContext({
webdriver: browser.driver,
tags: ['javascript driver']
}));
browser.reportingClient = reportingClient;
var myReporter = {
specStarted: function (result) {
reportingClient.testStart(result.fullName);
},
specDone: function (result) {
if (result.status === 'failed') {
const failure = result.failedExpectations[result.failedExpectations.length - 1];
reportingClient.testStop({
status: Reporting.Constants.results.failed,
message: `${failure.message} ${failure.stack}`
});
} else {
reportingClient.testStop({
status: Reporting.Constants.results.passed
});
}
}
}
jasmine.getEnv().addReporter(myReporter);
}
}
While running this I'm getting below error:
An error was thrown in an afterAll
AfterAll JavascriptError: javascript error: end is not defined
(Session info: chrome=90.0.4430.212)
(Driver info: chromedriver=90.0.4430.24 (4c6d850f087da467d926e8eddb76550aed655991-refs/branch-heads/4430#{#429}),platform=Windows NT 10.0.19042 x86_64)

How to make local connections to crossbrowsertesting.com with Protractor?

How can I test my Angular Pages with Protractor in my local network at crosbrowsertesting.com? I installed "npm i cbt_tunnels" and my protractor.conf looks like this:
const cbt = require('cbt_tunnels');
export.config= {
baseUrl: 'http://localhost:4200/',
framework: 'jasmine',
directConnect: false,
seleniumAddress: 'http://<myusername>:<mykey>#hub.crossbrowsertesting.com:80/wd/hub',
capabilities : {
name : 'protractor test', // this will show up in the UI
// these are important :)
browserName : "firefox",
browser_api_name : 'FF39', // change this according to what browser you are using
os_api_name : 'Win10', // change this for the OS you are using
screen_resolution : '1024x768', // change this for the resolution
record_video : 'true',
record_network : 'true',
record_snapshot : 'true',
acceptInsecureCerts: 'true',
tunnel: 'true'
},
onComplete: () => {
browser.quit();
},
onPrepare() {
cbt.start({"username": "<myusername>", "authkey":
"<mykey>"}, function (err) {
if (!err) console.log("cbt success");
});
}
I can see the test running at crossbrowsertesting.com but the browser there says:
waiting for localhost
What is missing?
As the commenter noted, you need to start the local connection before you can actually use the local connection feature.
In this case, you will want to use this line:
'cbt.start({"username":"USERNAME","authkey":"AUTHKEY"},function(err){ if(!err) do stuff })'
from the documentation; this will allow you to automatically start the test once the local connection has been set up correctly.
In this case, do stuff is everything to run your tests (scaffolding/setup can be done externally).
Something like this is what you're really after
const cbt = require('cbt_tunnels');
cbt.start({"username":"USERNAME","authkey":"AUTHKEY"},
function(err){
if(!err) do stuff
});
Edit:
It looks like you want to start the tunnel in beforeLaunch, instead of in onPrepare, and it needs to be set as a promise. Something like this:
beforeLaunch: () => {
return new Promise( (resolve, reject) => {
cbt.start({"username": "<your email here>", "authkey": "<your auth here>"}, function (err) {
if (!err) {
console.log("cbt success");
return resolve();
}
return reject(err);
});
})
}

testing a site not working in internet explorer-values not able to enter in fields

I am using protractor version 5.2.2 and cucumber-protractor framework, I have started practising testing for the LinkedIn site, but when I use the internet explorer browser it is only able to open the LinkedIn URL as mentioned in the config file and no scenarios are being executed, can anybody help me?
//config file
var params = require('./browsers.js');
var browser = params.browser;
var multiCapabilities = browser.split(',').map(function(browserName){
return {
browserName: browserName.trim()
};
})
var moment = require('moment')
var timeStamp = moment().format('YYYYMMDD_hhmmss');
exports.config = {
seleniumAddress: 'http://127.0.0.1:4444/wd/hub',
getPageTimeout: 60000,
allScriptsTimeout: 500000,
framework: 'custom',
frameworkPath: require.resolve('protractor-cucumber-framework'),
// Capabilities to be passed to the webdriver instance.
multiCapabilities: multiCapabilities,
// Spec patterns are relative to the current working directory when
// protractor is called.
specs: ['Features/*.feature'],
baseUrl: 'https://www.linkedin.com/',
cucumberOpts: {
require: 'Features/step_definition/searchstep_linkedin.js',
tags: false,
plugin: ['pretty'],
format: 'json:reports/report'+timeStamp+' '+browser+'/results.json',
profile: false,
'no-source': true
},
plugins: [{
package: 'protractor-multiple-cucumber-html-reporter-plugin',
options:{
automaticallyGenerateReport: true,
}
}]
};
//Feature file
Background: I need to go linked in site
Given I go to url ""
Scenario: Should not login with blank username and password
Then I wait for "2000"
When I enter " " in "#login-email"
When I enter " " in "#login-password"
Then I click on "#login-submit"
Then I should see ""
//Spec File
Given(/^I go to url "(.*)"$/, function (url){
return browser.get(url);
});
When(/^I enter "(.*)" in "(.*)"$/, function (value,locator){ /**/
return element(by.xpath(locator)).sendKeys(value);
});
Then(/^I should see "(.*)"$/, function (url){ /**/
browser.sleep(2000);
return
expect(browser.getCurrentUrl()).to.eventually.equal(browser.baseUrl
+ url);
});
Then(/^I click on "(.*)"$/, function (locator){ /**/
return return element(by.xpath(locator)).click();
});

Protractor: commands in afterLaunch don't run

I'm trying to send an email out with results after tests have finished running.
When I put the sendgrid call in the onComplete section, then the email sends. However, the report is empty since it hasn't finished saving.
If I put the sendgrid call into the afterLaunch section, then the file is saved. However, it doesn't seem to run the sendgrid command.
This is the config that I am using:
var HtmlReporter = require ('protractor-jasmine2-html-reporter');
var browser = "chrome";
var environment = "dev";
var pname = "";
var pversion = "";
var dname = "";
var selenium_address = "http://localhost:4444/wd/hub";
var folder_name = (new Date()).toString().split(' ').splice(0,3).join('');
var report_folder = "./test/e2e/reports/" + folder_name + "_" + browser + "_" + environment + "/";
var reporter = new HtmlReporter({
savePath: report_folder,
takeScreenshots: false,
cleanDestination: true,
fileName: 'CE_Smoketest'
});
function test_function() {
var report = report_folder + 'CE_Smoketest.html'
var sendgrid = require('sendgrid')('xxxxx', 'xxxxxxxxx');
var email = new sendgrid.Email();
email.addTo("destination#mail.com");
email.setFrom("Smoketest#mail.com");
email.setSubject("Smoketest");
email.setHtml("Smoketest results");
email.addFile({filename: report});
sendgrid.send(email);
}
exports.config = {
//appium setup
seleniumAddress: selenium_address,
multiCapabilities: [
{
'browserName' : browser,
platformName : pname,
platformVersion : pversion,
deviceName: dname
}
],
getPageTimeout: 50000,
allScriptsTimeout: 50000,
jasmineNodeOpts: {
defaultTimeoutInterval: 50000,
isVerbose: true
},
onPrepare: function() {
jasmine.getEnv().addReporter(reporter);
},
onComplete: function(exitCode) {
test_function();
},
afterLaunch: function(exitCode) {
test_function();
}
}
Any ideas as to why afterLaunch doesn't send the email?
In afterLaunch methods, Webdriver instance have been shutdow(Not available). That's you code will get executed. Check description of afterLaunch() method below:
/**
* A callback function called once all tests have finished running and
* the WebDriver instance has been shut down. It is passed the exit
code
* (0 if the tests passed). afterLaunch must return a promise if you
want
* asynchronous code to be executed before the program exits.
* This is called only once before the program exits (after onCleanUp).
*/
Suresh is right, you must return a promise if you want asynchronous code to be executed before the program exits
Try this:
1- Declare new var
var q = require('q');
2- Refactor your afterLaunch
afterLaunch: function(exitCode) {
return q.fcall(function () {
test_function();
}).delay(1000);
}

Emberjs-CLI web socket

I am attempting to create a web socket for use in my EmberJS app that I have created using the cli. I am a bit unsure of what logic goes where, so let me know if I did this incorrectly.
I have an Adapter that should create a connection and then handle any request that is made to the server that I am connecting to. I am unsure of how to reference this socket in my controller.
export default DS.Adapter.extend({
url: '<my connection bruh>',
qSocket: null,
deferred: $.Deferred(),
defResolve: function(res){
this.deferred.resolve(res);
},
init: function(uri){
var qsservice = this;
if(arguments.length==1&&uri.length>4){
this.url=uri;
}
this.qSocket = new WebSocket(this.url);
this.qSocket.onopen = function(evt){console.log('CONNECTED');};
this.qSocket.onclose = function(evt){console.log('DISCONNECTED');};
this.qSocket.onmessage = function(evt){console.log('RESPONSE: '+evt.data);
qsservice.deferred.resolve(evt.data);};
this.qSocket.onerror = function(evt){console.log('ERROR');
qsservice.deferred.reject(evt);};
},
sendMessage: function (msg) {
return this.qSocket.send(msg);
},
disconnect: function(){
this.qSocket.close();
},
isConnected: function(){
return this.qSocket ? true : false;
},
getDocList: function(){
this.qSocket.send(JSON.stringify(GetDocList));
return this.deferred.promise();
}
});
How would I call any of these functions from, say, the index controller?