refactored server-side tests

This commit is contained in:
David Baldwynn 2017-04-23 12:46:15 -07:00
parent 3f02a67686
commit 5798f5aa95
No known key found for this signature in database
GPG key ID: 15D1C13202224A9B
7 changed files with 168 additions and 214 deletions

View file

@ -136,7 +136,7 @@ var UserSchema = new Schema({
unique: true, unique: true,
index: true, index: true,
sparse: true sparse: true
}, }
}); });
UserSchema.virtual('displayName').get(function () { UserSchema.virtual('displayName').get(function () {

View file

@ -16,13 +16,13 @@ module.exports = function(app) {
.get(core.redoc); .get(core.redoc);
if(!config.subdomainsDisabled) { if(!config.subdomainsDisabled) {
app.route('/subdomain/:userSlug((?!api$)[A-Za-z0-9]+)/') app.route('/subdomain/:userSubdomain((?!api$)[A-Za-z0-9]+)/')
.get(core.form); .get(core.form);
app.route('/subdomain/:userSlug((?!api$)[A-Za-z0-9]+)/forms/:formId([a-zA-Z0-9]+)') app.route('/subdomain/:userSubdomain((?!api$)[A-Za-z0-9]+)/forms/:formId([a-zA-Z0-9]+)')
.post(forms.createSubmission); .post(forms.createSubmission);
app.route('/subdomain/:userSlug((?!api$)[A-Za-z0-9]+)/forms/:formId([a-zA-Z0-9]+)/render') app.route('/subdomain/:userSubdomain((?!api$)[A-Za-z0-9]+)/forms/:formId([a-zA-Z0-9]+)/render')
.get(forms.readForRender); .get(forms.readForRender);
} else { } else {
app.route('/view/') app.route('/view/')

View file

@ -1,4 +1,5 @@
'use strict'; 'use strict';
process.env.NODE_ENV = 'test';
var should = require('should'), var should = require('should'),
lodash = require('lodash'), lodash = require('lodash'),
@ -14,7 +15,14 @@ var should = require('should'),
/** /**
* Globals * Globals
*/ */
var credentials, user, myForm, userSession; var user, myForm, userSession;
// Create user credentials
var credentials = {
username: 'test1234',
email: 'test1234@test.com',
password: 'password'
};
/** /**
* Form routes tests * Form routes tests
@ -23,13 +31,6 @@ describe('Form Routes Unit tests', function() {
beforeEach(function(done) { beforeEach(function(done) {
// Create user credentials
credentials = {
username: 'test',
email: 'test@test.com',
password: 'password'
};
// Create a new user // Create a new user
user = new User({ user = new User({
firstName: 'Full', firstName: 'Full',
@ -52,7 +53,8 @@ describe('Form Routes Unit tests', function() {
new Field({'fieldType':'textfield', 'title':'First Name', 'fieldValue': ''}), new Field({'fieldType':'textfield', 'title':'First Name', 'fieldValue': ''}),
new Field({'fieldType':'checkbox', 'title':'nascar', 'fieldValue': ''}), new Field({'fieldType':'checkbox', 'title':'nascar', 'fieldValue': ''}),
new Field({'fieldType':'checkbox', 'title':'hockey', 'fieldValue': ''}) new Field({'fieldType':'checkbox', 'title':'hockey', 'fieldValue': ''})
] ],
isLive: true
}; };
//Initialize Session //Initialize Session
@ -62,52 +64,6 @@ describe('Form Routes Unit tests', function() {
}); });
}); });
it(' > should be able to upload a PDF to Form if signed in', function(done) {
userSession.post('/auth/signin')
.send(credentials)
.expect('Content-Type', /json/)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) return done(signinErr);
var user = signinRes.body;
var userId = user._id;
// Save a new Form
userSession.post('/forms')
.send({form: myForm})
.expect('Content-Type', /json/)
.expect(200)
.end(function(FormSaveErr, FormSaveRes) {
// Handle Form save error
if (FormSaveErr) return done(FormSaveErr);
// Get a list of Forms
userSession.get('/forms')
.expect('Content-Type', /json/)
.expect(200)
.end(function(FormsGetErr, FormsGetRes) {
// Handle Form save error
if (FormsGetErr) return done(FormsGetErr);
// Get Forms list
var Forms = FormsGetRes.body;
// Set assertions
(Forms[0].admin).should.equal(userId);
(Forms[0].title).should.match('Form Title');
// Call the assertion callback
done();
});
});
});
});
it(' > should not be able to create a Form if not logged in', function(done) { it(' > should not be able to create a Form if not logged in', function(done) {
userSession.post('/forms') userSession.post('/forms')
.send({form: myForm}) .send({form: myForm})
@ -127,71 +83,6 @@ describe('Form Routes Unit tests', function() {
}); });
}); });
it(' > should not be able to save a Form if no title is provided', function(done) {
// Set Form with a invalid title field
myForm.title = '';
userSession.post('/auth/signin')
.send(credentials)
.expect('Content-Type', /json/)
.expect(200)
.end(function(signinErr, signinRes) {
should.not.exist(signinErr);
// Save a new Form
userSession.post('/forms')
.send({form: myForm})
.expect(400)
.end(function(FormSaveErr, FormSaveRes) {
// Set message assertion
(FormSaveRes.body.message).should.equal('Form Title cannot be blank');
done();
});
});
});
it(' > should be able to update a Form if signed in', function(done) {
userSession.post('/auth/signin')
.send(credentials)
.expect('Content-Type', /json/)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) return done(signinErr);
// Save a new Form
userSession.post('/forms')
.send({form: myForm})
.expect('Content-Type', /json/)
.expect(200)
.end(function(FormSaveErr, FormSaveRes) {
// Handle Form save error
if (FormSaveErr) return done(FormSaveErr);
// Update Form title
myForm.title = 'WHY YOU GOTTA BE SO MEAN?';
// Update an existing Form
userSession.put('/forms/' + FormSaveRes.body._id)
.send({form: myForm})
.expect('Content-Type', /json/)
.expect(200)
.end(function(FormUpdateErr, FormUpdateRes) {
// Handle Form update error
if (FormUpdateErr) done(FormUpdateErr);
// Set assertions
(FormUpdateRes.body._id).should.equal(FormSaveRes.body._id);
(FormUpdateRes.body.title).should.match('WHY YOU GOTTA BE SO MEAN?');
// Call the assertion callback
done();
});
});
});
});
it(' > should be able to read/get a Form if not signed in', function(done) { it(' > should be able to read/get a Form if not signed in', function(done) {
// Create new Form model instance // Create new Form model instance
var FormObj = new Form(myForm); var FormObj = new Form(myForm);
@ -200,8 +91,7 @@ describe('Form Routes Unit tests', function() {
FormObj.save(function(err, form) { FormObj.save(function(err, form) {
if(err) return done(err); if(err) return done(err);
userSession.get('/forms/' + form._id) userSession.get('/subdomain/' + credentials.username + '/forms/' + form._id + '/render')
.expect('Content-Type', /json/)
.expect(200) .expect(200)
.end(function(err, res) { .end(function(err, res) {
if(err) return done(err) if(err) return done(err)
@ -215,46 +105,6 @@ describe('Form Routes Unit tests', function() {
}); });
}); });
it(' > should be able to delete a Form if signed in', function(done) {
userSession.post('/auth/signin')
.send(credentials)
.expect('Content-Type', /json/)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) return done(signinErr);
// Save a new Form
userSession.post('/forms')
.send({form: myForm})
.expect('Content-Type', /json/)
.expect(200)
.end(function(FormSaveErr, FormSaveRes) {
// Handle Form save error
if (FormSaveErr) return done(FormSaveErr);
// Delete an existing Form
userSession.delete('/forms/' + FormSaveRes.body._id)
.send(myForm)
.expect('Content-Type', /json/)
.expect(200)
.end(function(FormDeleteErr, FormDeleteRes) {
// Handle Form error error
if (FormDeleteErr) return done(FormDeleteErr);
// Set assertions
should.exist(FormDeleteRes.body);
// (FormDeleteRes.body._id).should.equal(FormSaveRes.body._id);
// Call the assertion callback
done();
});
});
});
});
it(' > should not be able to delete an Form if not signed in', function(done) { it(' > should not be able to delete an Form if not signed in', function(done) {
// Set Form user // Set Form user
myForm.admin = user; myForm.admin = user;
@ -276,57 +126,159 @@ describe('Form Routes Unit tests', function() {
}); });
}); });
describe(' > Login as User', function() {
//Initialize Session
var authenticatedSession;
var loginSession = Session(app);
describe(' > Login and Save a new Form >', function() { beforeEach(function(done) {
var _user, _form, _userSession = Session(app); loginSession.post('/auth/signin')
it('should be able to login as user', function(done){
_userSession.post('/auth/signin')
.send(credentials) .send(credentials)
.expect('Content-Type', /json/) .expect('Content-Type', /json/)
.expect(200) .expect(200)
.end(function(signinErr, signinRes) { .end(function(signinErr, signinRes) {
if(signinErr) {
return done(signinErr);
}
// Handle signin error authenticatedSession = loginSession;
if (signinErr) return done(signinErr); return done();
});
});
_user = signinRes.body; it(' > should not be able to save a Form if no title is provided', function(done) {
// Save a new Form // Set Form with a invalid title field
_userSession.post('/forms') myForm.title = '';
.send({form: myForm})
.expect('Content-Type', /json/)
.expect(200)
.end(function(FormSaveErr, FormSaveRes) {
// Handle Form save error
if (FormSaveErr) return done(FormSaveErr);
_form = FormSaveRes.body;
// Get a list of Forms // Save a new Form
_userSession.get('/forms/'+_form._id) authenticatedSession.post('/forms')
.expect('Content-Type', /json/) .send({form: myForm})
.expect(200) .expect(405)
.end(function(FormsGetErr, FormsGetRes) { .end(function(FormSaveErr, FormSaveRes) {
// Handle Form save error // Handle Form save error
if (FormsGetErr) return done(FormsGetErr); if (FormSaveErr) {
return done(FormSaveErr);
}
var fetchedForm = FormsGetRes.body; // Set message assertion
// Set assertions (FormSaveRes.body.message).should.equal('Form Title cannot be blank');
(fetchedForm.admin._id).should.equal(_user._id);
(fetchedForm.title).should.match(_form.title);
// Call the assertion callback done();
done(); });
});
});
});
});
after('should be able to signout user', function(done){
userSession.get('/auth/signout')
.end(function(signoutErr, signoutRes) {
});
it(' > should be able to update a Form if signed in', function(done) {
// Save a new Form
loginSession.post('/forms')
.send({form: myForm})
.expect('Content-Type', /json/)
.expect(200)
.end(function(FormSaveErr, FormSaveRes) {
// Handle Form save error
if (FormSaveErr) {
return done(FormSaveErr);
}
// Update Form title
myForm.title = 'WHY YOU GOTTA BE SO MEAN?';
// Update an existing Form
loginSession.put('/forms/' + FormSaveRes.body._id)
.send({form: myForm})
.expect('Content-Type', /json/)
.expect(200)
.end(function(FormUpdateErr, FormUpdateRes) {
// Handle Form update error
if (FormUpdateErr){
done(FormUpdateErr);
}
// Set assertions
(FormUpdateRes.body._id).should.equal(FormSaveRes.body._id);
(FormUpdateRes.body.title).should.match('WHY YOU GOTTA BE SO MEAN?');
// Call the assertion callback
done();
});
});
});
it(' > should be able to delete a Form if signed in', function(done) {
// Save a new Form
loginSession.post('/forms')
.send({form: myForm})
.expect('Content-Type', /json/)
.expect(200)
.end(function(FormSaveErr, FormSaveRes) {
// Handle Form save error
if (FormSaveErr) {
return done(FormSaveErr);
}
// Delete an existing Form
loginSession.delete('/forms/' + FormSaveRes.body._id)
.send(myForm)
.expect('Content-Type', /json/)
.expect(200)
.end(function(FormDeleteErr, FormDeleteRes) {
// Handle Form error error
if (FormDeleteErr) {
return done(FormDeleteErr);
}
// Set assertions
should.exist(FormDeleteRes.body);
(FormDeleteRes.body._id).should.equal(FormSaveRes.body._id);
// Call the assertion callback
done();
});
});
});
it('should be able to save new form while logged in', function(done){
// Save a new Form
authenticatedSession.post('/forms')
.send({form: myForm})
.expect('Content-Type', /json/)
.expect(200)
.end(function(FormSaveErr, FormSaveRes) {
// Handle Form save error
if (FormSaveErr) return done(FormSaveErr);
var _form = FormSaveRes.body;
// Get a list of Forms
authenticatedSession.get('/forms/'+_form._id)
.expect('Content-Type', /json/)
.expect(200)
.end(function(FormsGetErr, FormsGetRes) {
// Handle Form save error
if (FormsGetErr) return done(FormsGetErr);
var fetchedForm = FormsGetRes.body;
// Set assertions
(fetchedForm.admin.email).should.equal(user.email);
(fetchedForm.title).should.match(_form.title);
// Call the assertion callback
done();
});
});
});
afterEach('should be able to signout user', function(done){
authenticatedSession.get('/auth/signout')
.expect(200)
.end(function(signoutErr, signoutRes) {
// Handle signout error // Handle signout error
if (signoutErr) return done(signoutErr); if (signoutErr) return done(signoutErr);
_userSession.destroy(); authenticatedSession.destroy();
done(); done();
}); });
}); });
}); });

View file

@ -37,7 +37,7 @@ describe('User CRUD tests', function() {
_User = { _User = {
email: credentials.email, email: credentials.email,
username: credentials.username, username: credentials.username,
password: credentials.password, password: credentials.password
}; };
//Initialize Session //Initialize Session
@ -101,9 +101,7 @@ describe('User CRUD tests', function() {
}); });
}); });
it(' > should be able to reset a User\'s password');
afterEach(function(done) { afterEach(function(done) {
User.remove().exec(function () { User.remove().exec(function () {
tmpUser.remove().exec(function(){ tmpUser.remove().exec(function(){

2
config/env/all.js vendored
View file

@ -58,7 +58,7 @@ module.exports = {
secure: false, secure: false,
// Only set the maxAge to null if the cookie shouldn't be expired // Only set the maxAge to null if the cookie shouldn't be expired
// at all. The cookie will expunge when the browser is closed. // at all. The cookie will expunge when the browser is closed.
maxAge: 24 * 60 * 60 * 1000, // 24 hours maxAge: 24 * 60 * 60 * 1000 // 24 hours
// To set the cookie in a specific domain uncomment the following // To set the cookie in a specific domain uncomment the following
// setting: // setting:
//domain: process.env.COOKIE_SESSION_URL || process.env.BASE_URL || '.tellform.com' //domain: process.env.COOKIE_SESSION_URL || process.env.BASE_URL || '.tellform.com'

5
config/env/test.js vendored
View file

@ -1,7 +1,7 @@
'use strict'; 'use strict';
module.exports = { module.exports = {
baseUrl: 'http://localhost:3000', baseUrl: '127.0.0.1:3001',
db: { db: {
uri: 'mongodb://localhost/mean-test', uri: 'mongodb://localhost/mean-test',
options: { options: {
@ -22,6 +22,9 @@ module.exports = {
app: { app: {
title: 'TellForm Test' title: 'TellForm Test'
}, },
sessionCookie: {
maxAge: 24 * 60 * 60 * 1000 // 24 hours
},
facebook: { facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID', clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',

View file

@ -5,7 +5,7 @@ var passport = require("passport");
module.exports.isAuthenticatedOrApiKey = function isAuthenticated(req, res, next) { module.exports.isAuthenticatedOrApiKey = function isAuthenticated(req, res, next) {
if (req.isAuthenticated()) { if (req.isAuthenticated()) {
return next(); return next();
} }
// Try authenticate with API KEY // Try authenticate with API KEY
if (req.headers.apikey || req.query.apikey || req.body.apikey) { if (req.headers.apikey || req.query.apikey || req.body.apikey) {
passport.authenticate("localapikey", function (err, user, info) { passport.authenticate("localapikey", function (err, user, info) {
@ -23,8 +23,9 @@ module.exports.isAuthenticatedOrApiKey = function isAuthenticated(req, res, next
}); });
})(req, res, next); })(req, res, next);
} } else {
return res.sendStatus(401); return res.sendStatus(401);
}
}; };
@ -32,7 +33,7 @@ module.exports.hasRole = function hasRole(roleRequired) {
if (!roleRequired) { if (!roleRequired) {
throw new Error("Required role needs to be set"); throw new Error("Required role needs to be set");
} }
return function(req, res, next) { return function(req, res, next) {
return module.exports.isAuthenticated(req, res, function() { return module.exports.isAuthenticated(req, res, function() {
if (req.user && req.user.roles && req.user.roles.indexOf(roleRequired) !== -1){ if (req.user && req.user.roles && req.user.roles.indexOf(roleRequired) !== -1){