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

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",
})

Related

How to mock and testing an FTP Connection with Mocha

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);

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,
},
};

POST request freezes after add body-parser

I'm build vue app, and for mine app need api request to server from client, also necessary proxy any request.
It's mine vue.config.js
const producer = require('./src/kafka/producer');
const bodyParser = require('body-parser')
module.exports = {
devServer: {
setup: function (app, server) {
app.use(bodyParser.json())
app.post('/send-message', function (req, res) {
producer.send(req.body)
.then(() => {
res.json({result: true, error: null});
})
.catch((e) => {
res.status(500).json({result: false, error: e});
})
});
},
proxy: {
'/v2/order/by-number': {
target: 'http://address-here'
}
}
}
};
As you can see so i'm use body-parser app.use(bodyParser.json())
After I added it, proxying stopped working for me. Request to /send-message freezes after show me error
Proxy error: Could not proxy request path-here from localhost:8080
to http://address-here
Internet searches have not led to a solution.
For a long time, i find a solution:
Add second param jsonParser to app.post()
See full example
const producer = require('./src/kafka/producer');
const bodyParser = require('body-parser')
const jsonParser = bodyParser.json({limit: '1mb'});
module.exports = {
devServer: {
setup: function (app, server) {
app.post('/send-message', jsonParser, function (req, res) {
producer.send(req.body)
.then(() => {
res.json({result: true, error: null});
})
.catch((e) => {
res.status(500).json({result: false, error: e});
})
});
},
proxy: {
'path': {
target: 'http://address-here'
}
}
}
};

In Hapi.js server is not starting

const Hapi=require('hapi');
//Init server
const server=new Hapi.Server();
//Add connection
server.connection({
port:3000,
host:'localhost'
});
//Home route
server.route({
method:'GET',
path:'/',
handler:(request,reply)=>{
reply('Hello World');
}
})
// Start Server
server.start((err) => {
if(err){
throw err;
}
console.log(`Server started at: ${server.info.uri}`);
});
Blockquote
This is my first hapi.js server for printing hello world in home page but shows server.connection is not a function and also handlers are not promising.
Plz help me.
Try this
const Hapi=require('hapi');
//Init server
const server = new Hapi.Server({ port: 3000, host: 'localhost' });
//Home route
server.route({
method: 'GET',
path: '/',
handler: function (request, h) {
return 'hello world';
}
});
// Start Server
server.start(err => {
if (err) {
// Fancy error handling here
console.error(err);
throw err;
}
console.log(`Server started at ${ server.info.uri }`);
});
Hapi v17.0.0^ is not supporting for multiple connections for a single server and no longer passing the reply function as the second argument
check you node.js version older versions does not support the latest hapi format. there seems to be alot of diiference betwwen older versions and newer versions of hapi.js
const Hapi = require('#hapi/hapi');
const port = process.env.PORT || 3000;
const init = async () => {
const server = Hapi.server({
port: port,
host: 'localhost'
});
server.route({
method: 'GET',
path: '/',
handler: (request, h) => {
return 'Hello World!';
}
});
await server.start();
console.log('Server running on %s', server.info.uri);
};
init();

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