How to get my node.js mocha test running? - javascript

I have developed a service in node.js and looking to create my first ever mocha test for this in a seperate file test.js, so I can run the test like this:
mocha test
I could not figure out how to get the reference to my app, routes.js:
var _ = require('underscore');
module.exports = function (app) {
app.post('/*', function (req, res) {
var schema={
type: Object,
"schema":
{
"totalRecords": {type:Number}
}
};
var isvalid = require('isvalid');
var validJson=true;
isvalid(req.body,schema
, function(err, validObj) {
if (!validObj) {
validJson = false;
}
handleRequest(validJson,res,err,req);
});
})
}
This is the server.js:
// set up ======================================================================
var express = require('express');
var app = express(); // create our app w/ express
var port = process.env.PORT || 8080; // set the port
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use (function (error, req, res, next){
res.setHeader('content-type', 'application/json');
res.status(400);
res.json({
"error": "errormsg"
});
});
// routes ======================================================================
require('./routes.js')(app);
// listen (start app with node server.js) ======================================
app.listen(port);
console.log("App listening on port " + port);
And finally test.js:
"use strict";
var request = require('supertest');
var assert = require('assert');
var express = require('express');
var app = express();
describe('testing filter', function() {
it('should return an error', function (done) {
request(app)
.post('/')
.send({"hh":"ss"})
.expect(400,{"error": "errormsg"})
.end(function (err, res) {
if (err) {
done(err);
} else {
done();
}
});
});
});

Create a separate file called app.js. The only purpose of this file would be to run the server. You'll also need to export your app object from server.js. So, your server.js would look like this
// set up ======================================================================
var express = require('express');
var app = express(); // create our app w/ express
var port = process.env.PORT || 8080; // set the port
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use (function (error, req, res, next){
res.setHeader('content-type', 'application/json');
res.status(400);
res.json({
"error": "errormsg"
});
});
// routes ======================================================================
require('./routes.js')(app);
module.exports = app;
Create a new file called app.js and put this inside of it
var app = require('./app');
var port = process.env.port || 8000;
app.listen(port, function() {
console.log("App listening on port " + port);
});
Now, inside of your test file, import your app as follows
var request = require('supertest');
var assert = require('assert');
var app = require('./app.js');
....
Note that I assume all your files are in the same directory. If you've put your test file in a different folder then you'll need to give the right path while requiring your app object.

Related

Waiting for localhost when trying to connect to node js server

when i run this , i should be able to get mysite at localhost:3000 . but when i go to localhost:3000 it is not loading. chrome is still showing waiting for localhost. This is the code . It is a simple node js blog that uses mongo db. I got it from this github https://github.com/pankajwp/node-js-blog
This is the code for server. Please help
i will add my mongodb credentials to mongoose.connect.
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
var expressLayouts = require('express-ejs-layouts');
var mongoose = require('mongoose');
mongoose.connect('');
var Schema = mongoose.Schema;
app.use('/assests',express.static(__dirname + '/public'));
app.use(expressLayouts);
app.use((req, res, next) => {
res.locals.baseUrl = req.baseUrl;
next();
});
// by default express will look for static files inside the filder called views
app.set('view engine', 'ejs');
// Controllers
var pageController = require('./controllers/pageController');
var postController = require('./controllers/postController');
var adminController = require('./controllers/adminController');
var randomController = require('./controllers/randomController');
randomController(app);
adminController(app, Schema, mongoose);
postController(app, Schema, mongoose);
pageController(app, Schema, mongoose);
// Listen
app.listen(port);
console.log('Listening on localhost:'+ port);
Following thing is wrong
// Listen
app.listen(port);
console.log('Listening on localhost:'+ port);
Right away after calling listen, app does not listen immediately to the specified port.
The code should be like following
app.listen(port, function() {
console.log(`Listening on localhost: ${port}!`);
})
What is happening here, listening to a port is a asynchronous task. It is accepting some callback to let you know, what is the status of your listening to the port. If successful, then callback is called.
What your code was doing is, whether the listening to port is success of not, it always prints Listening on localhost: xxxx.
Example taken from directly Express Hello world.
Try This:
const express = require('express');
const ejs = require('ejs');
const expressLayouts = require('express-ejs-layouts');
const mongoose = require('mongoose');
const app = express();
const port = process.env.PORT || 3000;
//Create Object like this
const Schema = new mongoose.Schema({
//your properties name goes here like:
name: {
type:String
}
});
app.use('/assests',express.static(__dirname + '/public'));
app.use(expressLayouts);
app.use((req, res, next) => {
res.locals.baseUrl = req.baseUrl;
next();
});
// by default express will look for static files inside the filder called views
app.set('view engine', 'ejs');
// Controllers
var pageController = require('./controllers/pageController');
var postController = require('./controllers/postController');
var adminController = require('./controllers/adminController');
var randomController = require('./controllers/randomController');
randomController(app);
adminController(app, Schema, mongoose);
postController(app, Schema, mongoose);
pageController(app, Schema, mongoose);
//db connection
mongoose
.connect('url goes here, ({useUnifiedTopology: true, useNewUrlParser:true}))
.then(() => console.log('MongoDB connected!!!'))
.catch(err => console.log(err));
app.listen(port, (req, res) => console.log(`Server is running at ${port}`));
you can try with adding this code jsut after declaring your port number.
app.use(bodyParser.json());
your updated code should looks like below and it should work on http://localhost:3000
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
app.use(bodyParser.json());
var expressLayouts = require('express-ejs-layouts');
var mongoose = require('mongoose');
mongoose.connect('');
var Schema = mongoose.Schema;
app.use('/assests',express.static(__dirname + '/public'));
app.use(expressLayouts);
app.use((req, res, next) => {
res.locals.baseUrl = req.baseUrl;
next();
});
// by default express will look for static files inside the filder called views
app.set('view engine', 'ejs');
// Controllers
var pageController = require('./controllers/pageController');
var postController = require('./controllers/postController');
var adminController = require('./controllers/adminController');
var randomController = require('./controllers/randomController');
randomController(app);
adminController(app, Schema, mongoose);
postController(app, Schema, mongoose);
pageController(app, Schema, mongoose);
// Listen
app.listen(port);
console.log('Listening on localhost:'+ port);

Creating an HTTPs server with Node.js and Express

var https = require('https'),
fs = require('fs'),
express = require('express'),
app = express();
// cookieParser = require('cookie-parser'),
// path = require('path'),
// bodyParser = require('body-parser'),
// https = require('http');
var key = fs.readFileSync('encryption/star_massifsolutions_com.key');
var cert = fs.readFileSync('encryption/massif_wildcard.crt');
var ca = fs.readFileSync('encryption/DigiCertCA.crt');
var httpsOptions = {
key: key,
cert: cert,
ca: ca
};
https.createServer(httpsOptions, app).listen(8000, function () {
console.log("server running at https://IP_ADDRESS:8000/")
});
app.get('/', function (req, res) {
res.header('Content-type', 'text/html');
return res.end('Hello World!');
});
// app.set('view', __dirname + '/views');
// app.use(bodyParser.urlencoded({
// extended: true
// }));
// app.use(bodyParser.json({
// limit: '500mb'
// }));
// app.use('/', express.static(path.join(__dirname, '/dist/basic-structure')));
// app.get('/**', function (req, res, next) {
// console.log(req, res, next);
// res.sendFile('index.html', {
// root: __dirname + '/dist/basic-structure'
// });
// });
console.log("listening to port 8000");
Here i have written hello world just to test my code.so in this case code runs but its not secure. I want my connection to be secure.In this case it shows deprecated http and shows certificate error.but and run unsecurly.
Again if I replace the hello world part with the commented part as shown in my code it doesn't even run with the deprecated http.if i replace the https with http it runs. I want help in running my edited code. If i am missing some points please let me know.
In short this code is running insecurly , i want to make it secure
Not sure if I understand well, but if by "the code is not running" you mean your app, then it seems your 2nd code set simply try to run a server but not your app
To my understanding, you are defining your app as express but you are not using it, so it will not be delivered
So my guess is that you will need to use the https server command with the app and its options to link everything together (https and app) as suggested by #lx1412
I would try this :
var express = require('express'),
cookieParser = require('cookie-parser'),
path = require('path'),
bodyParser = require('body-parser'),
// https = require('http'),
https = require('https'),
app = express(),
fs = require('fs');
var key = fs.readFileSync('encryption/star_massifsolutions_com.key');
var cert = fs.readFileSync( 'encryption/massif_wildcard.crt' );
var ca = fs.readFileSync( 'encryption/DigiCertCA.crt' );
var httpsOptions = {
key: key,
cert: cert,
ca: ca
};
app.set('view',__dirname+'/views');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json({limit: '500mb'}));
app.use('/', express.static(path.join(__dirname,'/dist/basic-structure')));
app.get('/**', function(req, res, next) {
console.log(req, res, next);
res.sendFile('index.html', { root: __dirname +
'/dist/basic-structure' });
});
// https.createServer(httpsOptions, (req, res) => {
// console.log("code works");
// res.writeHead(200);
// res.end('hello world\n');
// }).listen(8000);
https.createServer(httpsOptions, app).listen(8000, function () {
console.log("code works");
res.writeHead(200);
res.end('hello world\n');
});
EDIT :
Can you simply try this and see how it behaves ?
Also, can you provide your deprecated http and certificate error ?
app.get('/', function (req, res) {
res.send('Hello World!');
});
https.createServer(httpsOptions, app).listen(8000, function () {
console.log("server running at https://IP_ADDRESS:8000/")
});
It's simple.
var express = require('express'),
cookieParser = require('cookie-parser'),
path = require('path'),
bodyParser = require('body-parser'),
http = require('http'),
app = express();
app.set('view',__dirname+'/views');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json({limit: '500mb'}));
app.use('/', express.static(path.join(__dirname,'/dist/basic-structure')));
app.get('/**', function(req, res, next) {
console.log(req, res, next);
res.sendFile('index.html', { root: __dirname +
'/dist/basic-structure' });
});
//Start Server
//app.listen(3004, function(){
// console.log('>>>3004')
//});
//complete your code here
https.createServer(httpsOptions,app).listen(8000);

nodejs problems passing a paramenter to module

I am having a headache trying to pass a variable to module.
In node.js I have the following distribution:
The node.js server (server.js):
// modules =================================================
var express = require('express');
var app = express();
// configuration ===========================================
app.set('port', process.env.PORT || 3000);
var myRoutes = require('./my.router')(app);
// Start the Server ===========================================
app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
exports = module.exports = app; // expose app
The router (my.router.js):
var myCtrl = require('./my.controller');
module.exports = function(app) {
app.get('/api/some', myCtrl.some);
app.get('/api/other', myCtrl.other);
}
The controller(my.controller.js):
exports.some = function(req, res, next) {
res.send('some');
};
exports.other = function(req, res, next) {
res.send('other');
}
This works ok. My problems come when I try to use socket.io and emit an event when /api/some is called.
I need the app object to create the server so I change the router to:
var myCtrl = require('./my.controller');
module.exports = function(app) {
var server = require('http').createServer(app);
var io = require('socket.io')(server);
server.listen(3001);
app.get('/api/some', myCtrl.something);
app.get('/api/other', myCtrl.other);
}
And I change the controller to emit the event when /api/some is called:
exports.some = function(req, res, next) {
io.sockets.emit('my_event', {});
res.send('some');
};
exports.other = function(req, res, next) {
res.send('other');
}
Inside the controller I need the io object to make this work.
It may sound simple to someone with a bit more knowledge of node.js but I am not capable of making it work.
I would need something like app.get('/api/some', myCtrl.something(io)) but this is not working...
Can't you just split your code:
var server = require('http').createServer(app);
var io = require('socket.io')(server);
At this stage you have your io, then
var myCtrl = require('./my.controller')(io);
You pass the io as a parameter to your controller which should then be a function like:
/* my.controller.js */
module.exports = function(io) {
some: function(req, res, next) {
io.sockets.emit('my_event', {});
res.send('some');
},
other: function(req, res, next) {
res.send('other');
}
}
Or something along those lines.
// modules =================================================
var express = require('express');
var app = express();
// configuration ===========================================
app.set('port', process.env.PORT || 3000);
var server = require('http').createServer(app);
app.io = require('socket.io')(server); //add io key to app
server.listen(3001);
require('./my.router')(app);
app.Controllers = {};
app.Controllers.myCtrl = require('./my.controller')(app); //pass app to controllers as well (not necessary but you can bootstrap your controllers at the start instead of requiring them in files)
//app.Controllers.anotherCtrl = require('./my.anotherController')(app); //example
// Start the Server ===========================================
app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
exports = module.exports = app; // expose app
Controller
module.exports = function(app) {
var Controller = {};
var io = app.io;
Controller.some = function(req, res, next) {
io.sockets.emit('my_event', {});
res.send('some');
};
Controller.other = function(req, res, next) {
res.send('other');
}
return Controller;
};
Route
module.exports = function(app) {
var myCtrl = app.Controllers.myCtrl;
app.get('/api/some', myCtrl.some);
app.get('/api/other', myCtrl.other);
}
You can use the request object to pass the data between different routes.
module.exports = function(app) {
var server = require('http').createServer(app);
var io = require('socket.io')(server);
server.listen(3001);
//middleware used to assign 'io' to the request object
function passIoObject(req, res, next) {
req.myIo = io;
next()
}
// either use app.use(passIoObject) if io should be available for all following routes
// or pass it only to specific routes
app.get('/api/some', passIoObject, myCtrl.something);
app.get('/api/other', myCtrl.other);
}
and in your main controller you would access it using:
exports.some = function(req, res, next) {
req.myIo.sockets.emit('my_event', {});
res.send('some');
}
Beside that you should avoid a construct like:
module.exports = function(app) {
var server = require('http').createServer(app);
var io = require('socket.io')(server);
server.listen(3001);
app.get('/api/some', myCtrl.something);
app.get('/api/other', myCtrl.other);
}
The larger the code becomes the more problems you will have with maintainability, because you will always need look into the require('./my.router') file to see which paths/prefix are handled by the code.
Instead write it that way:
module.exports = function(app) {
var server = require('http').createServer(app);
var io = require('socket.io')(server);
server.listen(3001);
var router = express.Router();
router.get('/some', myCtrl.something);
router.get('/other', myCtrl.other);
return router;
}
And in server.js
var myRoutes = require('./my.router')(app);
app.use('/api', myRoutes);

Express routing error Cannot Get /api/name

Having some trouble setting up the restful API for my express app.
Here is my app.js:
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
methodOverride = require('method-override');
routes = require('./routes'),
api = require('./routes/api'),
port = process.env.PORT || 3000;
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(bodyParser.urlencoded({extended: true}));
// Page Routes
app.get('/', routes.index);
app.get('/partials/:filename', routes.partials);
// // API Routes
app.get('/api/name', api.name);
app.listen(port, function() {
console.log('Listening on port ' + port);
});
In /routes/api.js I have the following test function:
exports.name = function (req, res) {
res.json({
name: 'Test'
});
};
Currently I get the following error when i go to http://my_ip/api/name
Cannot GET /api/name
Any ideas?
Thanks
The following code is working for me. I think there is some issue with your routes package. Can you share the code of 'routes' package and file structure ?
app.js
var express = require('express'),
app = express(),
routes = require('./routes');
api = require('./routes/api'),
port = process.env.PORT || 3000;
// Page Routes
app.get('/', routes.index);
// API Routes
app.get('/api/name', api.name);
app.listen(port, function() {
console.log('Listening on port ' + port);
});
/routes/api.js
exports.name = function (req, res) {
res.json({
name: 'Test'
});
};
/routes.js
exports.index = function (req, res) {
res.json({
name: 'Index'
});
};

Node app route is not working

Im fairly new to node JS and I've created the following 3 files and when save the application I got error
http.createServer(app).listen(**app.get('port')**, function(){
the error is undefined is not a function
I use nodemon and I see the error in the terminal
I want to keep the structure of the files(to initiate the server from different file - server.js )since I want to use TDD .
this is the files
server.js
var http = require('http');
app = require('./app');
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
app.js
module.exports = function() {
var express = require('express'),
app = express();
app.set('port', process.env.PORT || 3000);
app.use(require('./controllers/requests'));
return app;
}
requests.js
var routers = require('express')
, router = express.Router()
router.get('/wild', function(req, res) {
debugger;
res.send('Wolf, Fox, Eagle')
})
module.exports = router
UPDATE
This is the update in the code
app.js
module.exports = function() {
var express = require('express'),
app = express();
app.set('port', process.env.PORT || 3000);
app.use(function(){
var routes = require('./controllers/requests') (app);
});
return app;
}
requests.js
**
module.exports = function (app) {
var express = require('express')
, router = express.Router();
app.get('/wild', function(req, res) {
res.send('Wolf, Fox, Eagle');
})
}
server.js
var http = require('http');
app = require('./app');
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});**
You should invoke the function returned by module containing app.
app = require('./app') ();
Moreover, in request.js file you should define routes on your app instance:
module.exports = function (app) {
app.get('/wild', function(req, res) {
res.send('Wolf, Fox, Eagle');
})
}
And in app.js:
app.use(function () {}) is used to define middlewares. Here you could call
var routes = require('./controllers/requests') (app);
EDIT
Please find here below the recap to answer your comments:
server.js
var http = require('http');
var app = require('./app') ();
http.createServer(app).listen(app.get('port'), function(err){
console.log('Express server listening on port ' + app.get('port'));
});
app.js
module.exports = function() {
var express = require('express'),
app = express();
app.set('port', process.env.PORT || 3000);
require('./controllers/requests')(app);
return app;
}
requests.js
module.exports = function (app) {
app.get('/wild', function(req, res) {
res.send('Wolf, Fox, Eagle')
});
}
Hope this helps!

Categories