How to mock and testing an FTP Connection with Mocha - testing

I am using the FTP library to establish an FTP connection to receive files from a specific location. I need to cover with tests mocha
const client = new Client();
const connect = {
host: 'host',
port: 21,
user: 'user',
password: 'password'
}
client.on('ready', function() {
client.list(function(err, list) {
if (err) throw err;
console.log(list);
client.end();
});
});
client.connect(connect);

Related

Can't connect to DB using node.js

I am new to node.js and try to connect to my database. I am using VS 2019 and when debugging while connecting to the local database (which is a copy from that on the server), it works fine and return the data but when I debug it when refer to the database on the server it didn't work.
I got the following error:
ConnectionError: Failed to connect to SQL5075.site4now.net:1433 - 12924:error:1425F102:SSL routines:ssl_choose_client_version:unsupported protocol:c:\ws\deps\openssl\openssl\ssl\statem\statem_lib.c:1994:
Can anyone help? Thank you
This is my code in VS2019:
var app = require('express')();
app.get('*', (req, res) => {
var sql = require("mssql");
// config for your database
var config = {
//This connection works fine
//user: 'sa',
//password: 'xxxxxxx',
//server: 'localhost',
//database: 'DB_9BD4_info'
// this connect to the server.
user: 'DB_admin',
password: 'xxxxxxx',
server: 'SQL50.xxxxxxx.net',
database: 'DB_9BD4_info'
};
(async function () {
try {
let pool = await sql.connect(config)
let result1 = await pool.request()
.query('select * from info')
// console.dir(result1)
// send records as a response
res.send(result1);
} catch (err) {
console.log(err)
}
})();
sql.on('error', err => {
// error handler
console.log(err);
});
});
//start listening
var port = process.env.PORT || 5321;
app.listen(port, function () {
console.log('Application started on ' + new Date());
console.log("Listening on " + port);
});
I've got the same error. What worked for me was this config object:
const sqlConfig = {
server: 'server',
database: 'database',
user: 'user',
password: 'password',
pool: {
max: 10,
min: 0,
idleTimeoutMillis: 30000,
},
options: {
instanceName: 'instance name',
trustServerCertificate: true,
encrypt: false,
},
};

server.close() gives "server not running" in afterEach mocha hook

I'm trying to run a test suite with mocha, the goal is to start the server beforeEach test case and then
close it afterEach test case.
But for some reason when the afterEach case ignites I get the following error:
Error [ERR_SERVER_NOT_RUNNING]: Server is not running.
The test case passes which means the server is up and running.
I Export the server like this from my app.js file:
var server = app.listen(3000, function () {
var port = server.address().port;
console.log("Example app listening at port %s", port);
});
module.exports = server; // Export server in order to use it in test files
My test file:
describe("loading express", function () {
var server;
before(function (done) {
User.deleteMany(done);
});
beforeEach(function () {
server = require("../app");
});
afterEach(function (done) {
server.close(done);
});
describe("Create user account with valid email address", function () {
describe("Route: POST /signup", () => {
it("201 HAPPY PATH", (done) => {
chai
.request(server)
.post("/signup")
.send({
email: "test23222#test.test",
password: "12345678",
firstname: "testtest",
lastname: "testtest",
})
.end((err, res) => {
res.should.have.status(201);
done();
});
});
});
});
});
I believe I need to export a promise.
This is what I got so far:
var server = new Promise(function (resolve, reject) {
app.listen(3000, function () {
var port = server.address().port;
console.log("Example app listening at port %s", port);
resolve();
});
}
module.exports = server; // Export server in order to use it in test files
in test suite:
var server = require('./app.js')
server.then(function() {
....
}
The server is closed by chai-http every time a request is served.
From the chai-http docs:
If you want to keep the server open, perhaps if you’re making multiple requests, you must call .keepOpen() after .request(), and manually close the server down:
E.g:
chai
.request(server)
.keepOpen() // <-- Here
.post("/signup")
.send({
email: "test23222#test.test",
password: "12345678",
firstname: "testtest",
lastname: "testtest",
})

Send email using Nodemailer with GoDaddy hosted email

I am trying to send an email using nodemailer and a custom email address configured through GoDaddy. Here is a screen shot of the "custom configurations" page in c-panel:
and my code:
const nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'Godaddy',
secureConnection: false,
auth: {
user: 'info#mywebsite.com',
pass: 'mypassword'
}
});
var mailOptions = {
from: 'info#mywebsite.com',
to: 'otheremail#gmail.com',
subject: 'Sending Email using Node.js',
text: 'That was easy!',
html: '<h1>Welcome</h1><p>That was easy!</p>'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
and my error log:
{ Error: connect EHOSTUNREACH 173.201.192.101:25
at Object.exports._errnoException (util.js:1012:11)
at exports._exceptionWithHostPort (util.js:1035:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1080:14)
code: 'ECONNECTION',
errno: 'EHOSTUNREACH',
syscall: 'connect',
address: '173.201.192.101',
port: 25,
command: 'CONN' }
I've tried changing the port number, making it secure vs non-ssl, using my website address as the host, and pretty much everything else I can think of. I have successfully sent an email from the godaddy email using one of the webmail clients. Has anyone else ever encountered this or have recommendations on things to try?
I am trying to send emails using nodemailer from Google Cloud Function using GoDaddy SMTP settings. I do not have Office365 enabled on my GoDaddy hosting. None of the above options worked for me today (12 November 2019). TLS need to be enabled.
I had to use the following configuration:
const mailTransport = nodemailer.createTransport({
host: "smtpout.secureserver.net",
secure: true,
secureConnection: false, // TLS requires secureConnection to be false
tls: {
ciphers:'SSLv3'
},
requireTLS:true,
port: 465,
debug: true,
auth: {
user: "put your godaddy hosted email here",
pass: "put your email password here"
}
});
Then, I could send a test email as follows:
const mailOptions = {
from: `put your godaddy hosted email here`,
to: `bharat.biswal#gmail.com`,
subject: `This is a Test Subject`,
text: `Hi Bharat
Happy Halloween!
If you need any help, please contact us.
Thank You. And Welcome!
Support Team
`,
};
mailTransport.sendMail(mailOptions).then(() => {
console.log('Email sent successfully');
}).catch((err) => {
console.log('Failed to send email');
console.error(err);
});
you should make some changes in your transporter:
var smtpTrans = nodeMailer.createTransport({
service: 'Godaddy',
host: "smtpout.secureserver.net",
secureConnection: true,
port: 465,
auth: {
user: "username",
pass: "password"
}
});
I realize this is an old post, but just wanted to add to this since the GoDaddy SMTP server has changed, just in case someone else comes across this and has the same problem I had. The answer by #tirmey did not work for me, but this did.
let nodemailer = require('nodemailer');
let mailerConfig = {
host: "smtp.office365.com",
secureConnection: true,
port: 587,
auth: {
user: "username#email.com",
pass: "password"
}
};
let transporter = nodemailer.createTransport(mailerConfig);
let mailOptions = {
from: mailerConfig.auth.user,
to: 'SomePerson#email.com',
subject: 'Some Subject',
html: `<body>` +
`<p>Hey Dude</p>` +
`</body>`
};
transporter.sendMail(mailOptions, function (error) {
if (error) {
console.log('error:', error);
} else {
console.log('good');
}
});
Solutions proposed above seem no longer valid, none of them worked for me. Following solution works for me:
const nodemailer = require('nodemailer');
const os = require('os');
let mailerConfig = {
host: os.hostname(),
port: 25,
};
let transporter = nodemailer.createTransport(mailerConfig);
transporter.sendMail({
from: '<from>',
to: '<to>',
subject: '<subject>',
text: '<text>'
}, (err, info) => {
console.log(info);
console.log(err);
});
I could solve the problem by using this code and some points that I brought them after codes:
const smtpTransport = nodemailer.createTransport({
host: "smtp.office365.com",
secure: false,
port: 587,
auth : {
user : 'info#my-domain.com',
pass : 'Password'
}
});
const mailOptions = {
to: 'target-mail#',
subject: 'Test 01',
html: 'Body',
from : 'info#resoluship.com'
};
await smtpTransport.sendMail(mailOptions);
Don't forget to use 'from' attribute in mailOptions
Don't use ',' in your 'from' attribute
For me, the solution for production shared hosting server was completely different than for testing.
It seems no authentication or credentials are required for it to work.
I created this code from this document describing how to use an SMTP relay server. You can use this with nodemailer. GoDaddy support told me I couldn't but I don't think they know about third party tools.
https://au.godaddy.com/help/send-form-mail-using-an-smtp-relay-server-953
async function main() {
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: 'localhost', //use localhost for linux cPanel hosting
port: 25,
secure: false,
// no need for authentication
tls: {
rejectUnauthorized: false
}
});
// send mail with defined transport object
let info = await transporter.sendMail({
to: "you#youremail.com", // list of receivers
subject: `New Message from ${name}`, // Subject line
text: `yourtext`, // plain text body
html: `your text in html`, // html body
headers: {
priority: 'high'
},
from: "you#youremail.com" // sender address
});
// send success page if successful
if (res.statusCode === 200) {
res.sendFile(path.join(__dirname, 'views/success.ejs'))
}
console.log("Message sent: %s", info.messageId, res.statusCode);
}
main().catch(console.error);
The most common problem with this error is the antivirus. So disable it for 10 minutes if you are testing it locally.

How to publish a message to rabbitmq using Mocha framework

Hi i'm unable to figure out how to connect to rabbitmq using Mocha & chai framework.
I've installed rabbitmq & erlang on my local & trying to connect to rabbitmq by starting the server on local.
The code i'm using is as below:
var chai = require('chai');
var chaiHttp = require('chai-http');
var request = chai.request;
var should = chai.should();
var expect = chai.expect;
var assert = chai.assert;
var supertest = require('supertest');
var fs = require('fs');
var amqp = require('amqplib/callback_api');
//Plugin for HTTP, etc.
chai.use(chaiHttp);
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
describe("Testing RabbitMQ : ", function () {
it("Send a message : ", function (done) {
amqp.connect('amqp://localhost:15672/', function (err, conn) {
conn.createChannel(function (err, ch) {
var q = 'hello';
ch.assertQueue(q, { durable: false });
// Note: on Node 6 Buffer.from(msg) should be used
ch.sendToQueue(q, new Buffer('Hello World!'));
console.log(" [x] Sent 'Hello World!'");
});
setTimeout(function () { conn.close(); process.exit(0) }, 500);
});
done();
});
it("Receive a message", function (done) {
amqp.connect('amqp://localhost:15672/', function (err, conn) {
conn.createChannel(function (err, ch) {
var q = 'hello';
ch.assertQueue(q, { durable: false });
console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", q);
ch.consume(q, function (msg) {
console.log(" [x] Received %s", msg.content.toString());
}, { noAck: true });
});
});
done();
});
})
So is there any other way to connect to rabbitmq & publish a message?
I've tried with amqp library, any sample code for connecting to rabbitmq will be helpful.
Can anyone make me understand how to connect to a specific queue to send a message, where the message can be published.
Any help would be really appreciated. Thank you.
You are specifying the wrong port. The default amqp port is 5672. If you are not changing the default port then you don't need to specify the port in amqp server url. That is instead of amqp://localhost:15672/, you can simply specify the url as amqp://localhost. I would like to give a working program for How to publish a message to rabbitmq using Mocha framework?.
I run the RabbitMQ server in my system using docker
docker run -d --hostname rabbit1 --name rabbit1 -e RABBITMQ_ERLANG_COOKIE=rabbitcluster -p 30000:5672 -p 30001:15672 rabbitmq:management
Then
// test.js
var chai = require('chai')
var amqp = require('amqplib/callback_api');
var chaiHttp = require('chai-http')
var should = chai.should()
chai.use(chaiHttp);
var config={
protocol: 'amqp',
hostname: 'localhost',
port: 30000,
username: 'guest',
password: 'guest',
}
var q="ex.queue";
var msg = "Hello World!";
describe('Testing RabbitMQ',function(){
it('Sending Message to RabbitMQ Server',function(done){
amqp.connect(config, function(err, conn) {
if(err){
console.log("connection error");
return;
}
conn.createConfirmChannel(function(err, ch) {
if(err){
return;
}
ch.assertQueue(q, {durable: true});
ch.sendToQueue(q, new Buffer(msg), {persistent: true},
function(err){
if(err){
console.log("msg resend err==>",err);
return;
}
else{
console.log(" [x] reSent '%s'", msg);
}
});
});
done();
setTimeout(function() { conn.close();}, 500);
});
});
});

Can't access Sails.js app instance in integration tests

I'm trying to write some integration tests in sailsjs. I have a bootstrap.test.js file that lifts my server in a global before as the docs suggest.
In my integration test when I try to pass my sails app to supertest I get an error:
app is not defined
agent = request.agent(app.hooks.http.app);
^
bootstrap.test.js
var Sails = require('sails'),
Barrels = require('barrels'),
app;
before(function(done) {
console.log('Global before hook'); // Never called?
this.timeout(5000);
Sails.lift({
log: {
level: 'error'
},
models: {
connection: 'test',
migrate: 'drop'
}
}, function(err, sails) {
app = sails;
if (err) return done(err);
var barrels = new Barrels();
fixtures = barrels.data;
barrels.populate(function(err) {
done(err, sails);
});
});
});
// Global after hook
after(function (done) {
console.log(); // Skip a line before displaying Sails lowering logs
Sails.lower(done);
});
integration test
var chai = require('chai'),
expect = chai.expect,
request = require('supertest'),
agent = request.agent(app.hooks.http.app);
describe('Species CRUD test', function() {
it('should not allow an unauthenticated user create a species', function(done){
var species = {
scientificName: 'Latin name',
commonName: 'Common name',
taxon: 'Amphibian',
leadOffice: 'Vero Beach',
range: ['Florida', 'Georgia']
};
agent.post('species')
.send(species)
.end(function(err, species) {
expect(err).to.exist;
expect(species).to.not.exist;
done();
});
});
});
I have been trying to make the integration test work for a few days now. This seems to be working fine in my environment. Maybe you can give it a try.
bootstrap.test.js
var Sails = require('sails');
var sails;
before(function(done)
{
Sails.lift({
log: {
level: 'error'
},
connections: {
testDB: {
adapter: 'sails-memory'
}
},
connection: 'testDB',
}, function(err, server)
{
sails = server;
if (err) return done(err);
done(err, sails);
});
});
after(function(done)
{
Sails.lower(done);
});
Test
var request = require('supertest');
it('should return all users', function(done){
request(sails.hooks.http.app)
.get('/user)
.expect(200)
.expect('Content-Type', /json/)
.end(function(err, res){
// check the response
done();
);
}
I place bootstrap.test.js on the root of my test folder and then use mocha to run the test.
mocha test/bootstrap.test.js test/**/*.test.js
Hope this help.
it seems that since version 3.x of mocha, nodejs global variables capabilities was removed. so if you need it, you should specifically pass it to your environment like that:
mocha --globals global test/bootstrap.test.js test/**/*.test.js
or
in your mocha.opts file :
#test/mocha.opts
--globals global