Mail listener on nodejs not disconnecting - javascript

I'm currently using mail-listener5 package to assert the number of emails in the Inbox of an email address.
My test framework is nightwatchjs.
Currently, my command script to get the number of emails from the email address inbox (titled getInboxEmails) is;
var {MailListener} = require('mail-listener5');
exports.command = function() {
this.perform(function(done) {
var mailListener = new MailListener({
username: '##########outlook.com',
password: '#########',
host: 'imap-mail.outlook.com',
port: 993,
tls: true,
connTimeout: 10000,
authTimeout: 5000,
tlsOptions: { rejectUnauthorized: false },
mailbox: 'Inbox',
searchFilter: ['ALL'],
markSeen: true,
fetchUnreadOnStart: false,
attachments: false,
});
mailListener.start();
mailListener.on('server:connected', function() {});
mailListener.on('mailbox', function(mailbox) {
var totalInboxMessages = (mailbox.messages.total);
console.log('Total number of Inbox emails: ', totalInboxMessages);
});
// mailListener.on('server:disconnected', function() {
// });
// mailListener.stop();
done();
});
};
And my nightwatchjs test script looks like this;
module.exports = {
'getting emails...': function (browser) {
browser.getInboxEmails();
},
'bfs': function (browser) {
browser.url('https://www.motorcyclenews.com/bikes-for-sale/****');
*...assertions, etc*
},
'closing the browser': function (browser) {
browser.browserEnd();
},
};
When I run this nightwatchjs script, the following is outputted;
however, the browser doesn't close.
I kind of expected this, as in my getInboxEmails command script included;
// mailListener.on('server:disconnected', function() {
// });
// mailListener.stop();
However, when I uncommented these two commands, I didn't get the number of emails displayed (but the test/browser correctly 'shut down'.
So the output was now;
So it appears that the number of emails is correctly displayed when the disconnect and stop are omitted, but the test doesn't cease.
And when the disconnect and stop are added, the number of emails is not displayed but the test finishes correctly.
And what I'd like to do is list the number of emails and for the test to end.
Any help would be greatly appreciated.

Yo need to init your mail listener in beforeAll part
and stop that in afterAll
the problem in your example is that your stop is reached in the init part so your mailbox listener will never be raised
mailListener.on('mailbox', function(mailbox) {
var totalInboxMessages = (mailbox.messages.total);
console.log('Total number of Inbox emails: ', totalInboxMessages);
});
Just do some staff as below
let mailListener ;
jest.beforeAll(() => {
mailListener = new MailListener({
username: '##########outlook.com',
password: '#########',
host: 'imap-mail.outlook.com',
port: 993,
tls: true,
connTimeout: 10000,
authTimeout: 5000,
tlsOptions: { rejectUnauthorized: false },
mailbox: 'Inbox',
searchFilter: ['ALL'],
markSeen: true,
fetchUnreadOnStart: false,
attachments: false,
});
mailListener.start();
mailListener.on('server:connected', function() {});
mailListener.on('mailbox', function(mailbox) {
var totalInboxMessages = (mailbox.messages.total);
console.log('Total number of Inbox emails: ', totalInboxMessages);
});
});
and finally in the end part of your tests
jest.afterAll(() => {
mailListener.stop();
});
wish this help

Related

cypress.origin throws error: (uncaught exception)Error: on only accepts instances of Function

I am using Cypress with Cucumber.
I am trying to test cross origin login but the origin method keeps on throwing error:
Code:
Given(/^the user login to the Test Page$/, function () {
cy.visit("https://example-originalURL");
cy.get("button").contains("Login").click();
const credentials = {
username: "hello",
password: "user",
};
cy.origin("https://example-newURL", { args: credentials }, ({ username, password }) => {
cy.get("#email", { timeout: 20000 }).type(username);
cy.get("#password").type(password, { log: false });
cy.get("button").contains("Login").click();
});
});
Cypress.config.js
module.exports = defineConfig({
projectId: "t7unhv",
e2e: {
setupNodeEvents(on, config) {
on("file:preprocessor", cucumber());
on('task', {
log(message) {
console.log(message +'\n\n');
return null;
},
});
},
specPattern: "./cypress/e2e/features/*.feature",
chromeWebSecurity: false,
experimentalSessionAndOrigin: true,
defaultCommandTimeout: 15000,
env: {
devCentralUrl: "https://***.dev.***.com.au/login",
testCentralUrl:
"https://***.test.***.com.au/login",
test***: "http://***.test.***.com.au",
dev***: "http://***.dev.***.com.au",
uat***: "https://***.uat.***.com.au",
dataSource: "",
environs: "test",
},
retries: {
runMode: 0,
},
pageLoadTimeout: 15000,
reporter: "mochawesome",
reporterOptions: {
reporterEnabled: "mochawesome",
mochawesomeReporterOptions: {
reportDir: "cypress/reports/mocha",
quite: true,
charts: true,
overwrite: false,
html: false,
json: true,
},
},
},
});
Error:
The following error originated from your test code, not from Cypress.
> on only accepts instances of Function
When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.
I have tried multiple syntax changes like not passing the credentials as optional argument to cy.origin.
If someone can provide a quick help, that will be great.
If the problem is in the test code, it is likely to be that newURL is undefined. The error message suggests the problem is in the app, but that might be a red herring.
Try just adding a fixed string for the cy.origin() key,
cy.origin('login', { args: credentials }, ({ username, password }) => {
...
})

cant download attachments using mail-listener2

iam using mail-listener2 to download files from an gmail account
it works and I can see the files on the mailListener.on("mail",) event but it looks like
files r not save on the attachments folder
on the file event the file.path is undefined so I am guessing it dit not saved...
why I can't see the files?
why there is a .on("attachment") event id i can see the files on "mail" event?
i only want to process png files, is there any filter i can use?
this is my code...
thanks
import path from "path";
var MailListener = require("mail-listener2");
export class InvoiceFileLisetner {
private readonly hostName: string = 'imap.gmail.com'
private readonly userName: string = 'username';
private readonly password: string = 'password';
private readonly port: number;
public Listen() {
var mailListener = new MailListener({
username: this.userName,
password: this.password,
host: this.hostName,
port: 993, // imap port
tls: true,
connTimeout: 10000, // Default by node-imap
authTimeout: 5000, // Default by node-imap,
debug: console.log, // Or your custom function with only one incoming argument. Default: null
tlsOptions: { rejectUnauthorized: false },
mailbox: "INBOX", // mailbox to monitor
searchFilter: ["UNSEEN"], // 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: path.join(__dirname, '\\attachments/') }
});
mailListener.start(); // start listening
mailListener.on("server:connected", function () {
console.log("imapConnected");
});
mailListener.on("server:disconnected", function () {
console.log("imapDisconnected");
});
mailListener.on("error", function (err) {
console.log(err);
});
mailListener.on("mail", function (mail, seqno, attributes) {
if (mail.attachments != undefined) {
let accountName = mail.subject;
let invoiceFile = null;
for (let index = 0; index < mail.attachments.length; index++) {
if (mail.attachments[index].contentType == 'application/vnd.ms-excel') {
}
}
}
// mail processing code goes here
});
mailListener.on("attachment", function (attachment) {
console.log(attachment.path);
});
}
}

Unable to retrieve email information in protractor

Referencing the information from the question Fetching values from email in protractor test case, I am still unable to reference the emails. In my test case, the 'expect' is not getting executed for some unknown reason to me.
Also if I use the line,
browser.controlFlow().await(getLastEmail()).then(...)
There is a 'browser.controlFlow(...).await is not a function error'
conf.js
var MailListener = require("mail-listener2")
exports.config = {
framework: 'jasmine2',
specs: ['./test.js'],
jasmineNodeOpts: { defaultTimeoutInterval: 360000 },
allScriptsTimeout: 60000,
onPrepare: function () {
var mailListener = new MailListener({
username: "username",
password: "password",
host: "imapPort",
port: 993, // imap port
secure: true,
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")
})
mailListener.on("error", function(err){
console.log(err)
})
mailListener.on("server:disconnected", function(){
console.log("imapDisconnected")
})
global.mailListener = mailListener
},
onCleanUp: function () {
mailListener.stop()
}
}
The test case:
describe('Email Testing', function () {
it('should login with a registration code sent to an email', function () {
//this line causes a 'browser.controlFlow(...).await is not a function' error
// browser.controlFlow().await(getLastEmail()).then(function (email) {
getLastEmail().then(function (email) {
// The expect does not get executed as it should fail
expect(email.subject).toEqual('My Subject')
})
})
})
function getLastEmail () {
var deferred = protractor.promise.defer()
console.log('Waiting for an email...')
mailListener.on('mail', function (mail) {
console.log('No Console Log Here!')
deferred.fulfill(mail)
})
return deferred.promise
}
I am not certain what I am missing in my test case to be able to read the subject or body of the email?
Ran into the same issue today. Turns out the API for the webdriver and ControlFlow has been updated and await has been changed to wait. Yeah, subtle difference. See the new API reference here: https://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/promise_exports_ControlFlow.html
To schedule a task for the wait condition, change your code to look like this:
browser.controlFlow().wait(getLastEmail()).then(...)
you would basically have to wrap that asynchronous code inside of a promise and the pass that promise/function into the flow.execute()
var flow = protractor.promise.controlFlow();
flow.execute( getLastEmail() ).then(function(email){
text = email.text
});

How to report angular pending requests on protractor timeouts?

I've been working on some protractor tests lately and from time to time some of my tests randomly fail with the following error:
DEBUG - WebDriver session successfully started with capabilities { caps_:
{ platform: 'LINUX',
acceptSslCerts: true,
javascriptEnabled: true,
browserName: 'chrome',
chrome: { userDataDir: '/tmp/.com.google.Chrome.czw4dR' },
rotatable: false,
locationContextEnabled: true,
mobileEmulationEnabled: false,
'webdriver.remote.sessionid': '3afc09d9-d06d-4c99-a788-d1118093c08d',
version: '40.0.2214.111',
takesHeapSnapshot: true,
cssSelectorsEnabled: true,
databaseEnabled: false,
handlesAlerts: true,
browserConnectionEnabled: false,
nativeEvents: true,
webStorageEnabled: true,
applicationCacheEnabled: false,
takesScreenshot: true } }
Started
token: a62e88d34991f4eef0894102e004e92032857700
.F...........................
Failures:
1) login form filled should fail on wrong credentials
Message:
Failed: Timed out waiting for Protractor to synchronize with the page after 11 seconds. Please see https://github.com/angular/protractor/blob/master/docs/faq.md
Looking at protractor documentation this error usually happens when there are pending $http requests or i'm using $timeout for something. I've tried setting a longer timeout for my tests(minutes) but it hasn't helped. My latest idea has been to report what requests are pending so i made the following Jasmine Reporter:
var AngulaRequestsReporter = function(dir){
dir = (dir || '/tmp/protractors/');
this.requests = function(testDescription) {
var fname = testDescription.replace(/\s/g, '_') + '.pending_requests';
mkdirp(dir);
browser.executeScript(function(){
try{
var $http = angular.injector(["ng"]).get("$http");
return $http.pendingRequests;
}catch(e){
return [];
}
}).then(function(pendingRequests){
var stream = fs.createWriteStream(path.join(dir, fname));
stream.write(util.inspect(pendingRequests, {showHidden: false, depth: null}));
stream.end();
});
};
return this;
};
// takes screenshot on each failed spec (including timeout)
AngulaRequestsReporter.prototype = {
specDone: function(result) {
if (result.status !== 'passed') {
this.requests(result.description );
}
}
};
However the result is always an empty []. Have you guys had this problem before and if so how did you solve it? Also, is there anything i can make to improve this reporter?

Connecting Sequelize to Postgres installed with Homebrew

I'm trying to use Sequelize to connect to my local install of Postgres. I installed it via Homebrew and have confirmed that I can connect and query the database just fine. When I run Sequelize it outputs valid queries (I ran them via console) but the database doesn't change and doesn't log any connection. My current code is:
var sequelize = new Sequelize('reliable_rabbit', 'mohammad', null, {
host: "127.0.0.1",
dialect: 'postgres',
define: { timestamps: true, paranoid: true, underscore: true }//,
});
I can connect to the database via: psql -d reliable_rabbit -U mohammad -h 127.0.0.1. I am using version 1.5.0-beta of Sequelize.
Edit:
In my entry point (app/app.js), logs nothing:
var models = require('./models');
models.Post.sync().success(function(){
console.log("Success!")
}).error(function(error){
console.log("Error: " + error);
});
app/models.js:
var Sequelize = require("sequelize")
var sequelize = new Sequelize('reliable_rabbit', 'mohammad', null, {
host: "127.0.0.1",
logging: console.log,
dialect: 'postgres',
define: { timestamps: true, paranoid: true, underscore: true }//,
});
exports.Post = require("../models/post")(sequelize);
and finally models/post.js:
var Sequelize = require("sequelize");
module.exports = function(sequelize) {
return sequelize.define('post', {
title: { type: Sequelize.STRING, validate: { notEmpty: true } },
permalink: { type: Sequelize.STRING, validate: { is: ["^[a-z]+[a-z\-][a-z]+$"] } },
content: { type: Sequelize.TEXT, validate: { notEmpty: true } },
published: { type: Sequelize.BOOLEAN, defaultValue: false },
published_at: { type: Sequelize.DATE }
},{
instanceMethods: {
generatePermalink: function() {
this.permalink = this.title.toLowerCase().replace(/[^a-z]/g, "-").replace(/^-+|-+$/g,'').replace(/\-{2,}/g, '-');
}
}
});
};
first of all i would recommend the use of sequelize.import. furthermore i'm wondering if you probably just forgot to sync the database? Please let me know if you need further details about those things :)

Categories

Resources