added test cases form form services

This commit is contained in:
David Baldwynn 2015-08-20 17:17:14 -07:00
parent 1fb36f9b4e
commit 6142afc91c
29 changed files with 851 additions and 367 deletions

7
config/env/all.js vendored
View file

@ -90,9 +90,14 @@ module.exports = {
'public/modules/*/*.js',
'public/modules/*/*[!tests]*/*.js'
],
views: [
'public/modules/*/views/*.html',
'public/modules/*/views/**/*.html'
],
tests: [
'public/lib/angular-mocks/angular-mocks.js',
'public/modules/*/tests/*.js'
'public/modules/*/tests/*.js',
'public/modules/*/tests/*/*.js',
]
}
};

View file

@ -15,12 +15,23 @@ module.exports = function(config) {
frameworks: ['jasmine'],
// List of files / patterns to load in the browser
files: bowerDep.concat(applicationConfiguration.assets.js, applicationConfiguration.assets.tests),
files: bowerDep.concat(applicationConfiguration.assets.js, applicationConfiguration.assets.tests, applicationConfiguration.assets.views),
// Test results reporter to use
// Possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['mocha', 'html', 'progress'],
preprocessors: {
'public/modules/**/*.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
stripPrefix: 'public/',
// the name of the Angular module to create
moduleName: 'module-templates'
},
// Web server port
port: 9876,

View file

@ -93,6 +93,7 @@
"karma-jasmine": "^0.2.3",
"karma-jasmine-html-reporter": "^0.1.8",
"karma-mocha-reporter": "^1.1.1",
"karma-ng-html2js-preprocessor": "^0.1.2",
"node-mandrill": "^1.0.1"
}
}

View file

@ -574,13 +574,14 @@ angular.module('forms').controller('ListFormsController', ['$rootScope', '$scope
};
$scope.duplicate = function(form_index){
var form = $scope.myforms[form_index];
delete form._id;
var form = _.clone($scope.myforms[form_index]);
form._id = '';
$http.post('/forms', {form: form})
.success(function(data, status, headers){
// console.log('form duplicated');
console.log('form duplicated');
$scope.myforms.splice(form_index+1, 0, data);
console.log($scope.myforms[3]._id);
}).error(function(errorResponse){
console.log(errorResponse);
$scope.error = errorResponse.data.message;
@ -592,7 +593,7 @@ angular.module('forms').controller('ListFormsController', ['$rootScope', '$scope
console.log($scope.forms.createForm);
var form = {};
form.title = $scope.forms.createForm.$modelValue;
form.title = $scope.forms.createForm.title.$modelValue;
form.language = $scope.forms.createForm.language.$modelValue;
if($scope.forms.createForm.$valid && $scope.forms.createForm.$dirty){
@ -630,32 +631,42 @@ angular.module('forms').controller('ListFormsController', ['$rootScope', '$scope
'use strict';
// Forms controller
angular.module('forms').controller('SubmitFormController', ['$scope', '$rootScope', '$stateParams', '$state', 'Forms', 'CurrentForm',
function($scope, $rootScope, $stateParams, $state, Forms, CurrentForm) {
angular.module('forms').controller('SubmitFormController', ['$scope', '$rootScope', '$stateParams', '$state', 'Forms', 'CurrentForm', 'Auth',
function($scope, $rootScope, $stateParams, $state, Forms, CurrentForm, Auth) {
$scope.authentication = Auth;
$scope.initForm = function(){
Forms.get({
formId: $stateParams.formId
}).$promise.then(
//success
function(form){
$scope.myform = form;
Forms.get({
formId: $stateParams.formId
}).$promise.then(
//success
function(form){
$scope.myform = form;
if(!$scope.myform.isLive){
// Show navbar if form is not public AND user IS loggedin
if($scope.authentication.isAuthenticated()){
$scope.hideNav = $rootScope.hideNav = false;
}
// Redirect if form is not public user IS NOT loggedin
else {
$scope.hideNav = $rootScope.hideNav = true;
$state.go('access_denied');
}
}else{
$scope.hideNav = $rootScope.hideNav = true;
}
},
//error
function( error ){
$scope.error = error.message;
console.log('ERROR: '+error.message);
throw new Error('Error: '+error.message);
// Show navbar if form is not public AND user is loggedin
if(!$scope.myform.isLive && $rootScope.authentication.isAuthenticated()){
$rootScope.hideNav = false;
}else if(!$scope.myform.isLive){
$state.go('access_denied');
}
console.log('$rootScope.hideNav: '+$rootScope.hideNav);
console.log('$scope.form.isLive: '+$scope.myform.isLive);
},
//error
function( error ){
$scope.error = error.message;
console.log('ERROR: '+error.message);
$state.go('access_denied');
});
$state.go('access_denied');
}
);
};
}
]);

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -1,32 +1,40 @@
'use strict';
// Forms controller
angular.module('forms').controller('SubmitFormController', ['$scope', '$rootScope', '$stateParams', '$state', 'Forms', 'CurrentForm',
function($scope, $rootScope, $stateParams, $state, Forms, CurrentForm) {
angular.module('forms').controller('SubmitFormController', ['$scope', '$rootScope', '$stateParams', '$state', 'Forms', 'CurrentForm', 'Auth',
function($scope, $rootScope, $stateParams, $state, Forms, CurrentForm, Auth) {
$scope.authentication = Auth;
$scope.initForm = function(){
Forms.get({
formId: $stateParams.formId
}).$promise.then(
//success
function(form){
$scope.myform = form;
Forms.get({
formId: $stateParams.formId
}).$promise.then(
//success
function(form){
$scope.myform = form;
// Show navbar if form is not public AND user is loggedin
if(!$scope.myform.isLive && $rootScope.authentication.isAuthenticated()){
$rootScope.hideNav = false;
}else if(!$scope.myform.isLive){
$state.go('access_denied');
}
console.log('$rootScope.hideNav: '+$rootScope.hideNav);
console.log('$scope.form.isLive: '+$scope.myform.isLive);
},
//error
function( error ){
$scope.error = error.message;
console.log('ERROR: '+error.message);
$state.go('access_denied');
});
if(!$scope.myform.isLive){
// Show navbar if form is not public AND user IS loggedin
if($scope.authentication.isAuthenticated()){
$scope.hideNav = $rootScope.hideNav = false;
}
// Redirect if form is not public user IS NOT loggedin
else {
$scope.hideNav = $rootScope.hideNav = true;
$state.go('access_denied');
}
}else{
$scope.hideNav = $rootScope.hideNav = true;
}
},
//error
function( error ){
$scope.error = error.message;
console.error('ERROR: '+error.message);
$state.go('access_denied');
}
);
};
}
]);

View file

@ -5,9 +5,6 @@ angular.module('forms').directive('autoSaveForm', ['$rootScope', '$timeout', fun
return {
require: ['^form'],
restrict: 'AE',
controller: function ($scope) {
},
link: function($scope, $element, $attrs, $ctrls) {
angular.element(document).ready(function() {

View file

@ -1,36 +0,0 @@
'use strict';
angular.module('forms').directive('changeFocus', function() {
return {
scope:{
focusDownId: '@',
focusUpId: '@',
},
link: function(scope, elem, attrs) {
// console.log('aoeuaoeuaoeuaou');
scope.focusUp = function(){
if(!scope.$first) {
console.log('focusUp');
elem[0].previousElementSibling.find('input').focus();
}
scope.apply();
};
scope.focusDown = function(){
if(!scope.$last) {
elem[0].nextElementSibling.focus();
}
scope.apply();
};
//Bind 'focus-down' click event to given dom element
angular.element('#' + scope.focusDownId).bind('click', function() {
scope.focusDown();
});
//Bind 'focus-up' click event to given dom element
angular.element('#' + scope.focusUpId).bind('click', function() {
scope.focusUp();
});
}
};
});

View file

@ -1,9 +1,9 @@
'use strict';
angular.module('forms').directive('configureFormDirective', ['$rootScope', '$http', 'Upload', '$timeout', 'timeCounter', 'Auth', 'FormFields',
function ($rootScope, $http, Upload, $timeout, timeCounter, Auth, FormFields) {
angular.module('forms').directive('configureFormDirective', ['$rootScope', '$http', 'Upload', '$timeout', 'TimeCounter', 'Auth', 'FormFields',
function ($rootScope, $http, Upload, $timeout, TimeCounter, Auth, FormFields) {
return {
templateUrl: './modules/forms/views/directiveViews/form/configure-form.client.view.html',
templateUrl: 'modules/forms/views/directiveViews/form/configure-form.client.view.html',
restrict: 'E',
scope: {
myform:'=',
@ -16,20 +16,20 @@ angular.module('forms').directive('configureFormDirective', ['$rootScope', '$htt
$scope.pdfLoading = false;
$scope.languages = $rootScope.languages;
var _current_upload = null;
this._current_upload = null;
$scope.resetForm = $rootScope.resetForm;
$scope.update = $rootScope.update;
var _unbindedPdfFields = $scope.pdfFields;
this._unbindedPdfFields = $scope.pdfFields;
//DAVID: TODO: finish this so we can create a Form.pdfFieldMap
// $scope.getUnbindedPdfFields = function(fieldType){
// _unbindedPdfFields = $scope.pdfFields
// this._unbindedPdfFields = $scope.pdfFields
// }
//PDF Functions
$scope.cancelUpload = function(){
_current_upload.abort();
this._current_upload.abort();
$scope.pdfLoading = false;
$scope.removePDF();
};
@ -43,13 +43,14 @@ angular.module('forms').directive('configureFormDirective', ['$rootScope', '$htt
};
$scope.uploadPDF = function(files) {
console.log(files)
if (files && files.length) {
// for (var i = 0; i < files.length; i++) {
var file = files[0];
console.log(file);
_current_upload = Upload.upload({
this._current_upload = Upload.upload({
url: '/upload/pdf',
fields: {
'user': $scope.user,
@ -60,6 +61,7 @@ angular.module('forms').directive('configureFormDirective', ['$rootScope', '$htt
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
$scope.log = 'progress: ' + progressPercentage + '% ' +
evt.config.file.name + '\n' + $scope.log;
$scope.pdfLoading = true;
}).success(function (data, status, headers, config) {
$scope.log = 'file ' + data.originalname + ' uploaded as '+ data.name +'. JSON: ' + JSON.stringify(data) + '\n' + $scope.log;

View file

@ -1,15 +1,13 @@
'use strict';
angular.module('forms')
.directive('editFormDirective', ['$rootScope', '$q', '$http', '$timeout', 'timeCounter', 'Auth', 'FormFields',
function ($rootScope, $q, $http, $timeout, timeCounter, Auth, FormFields) {
angular.module('forms').directive('editFormDirective', ['$rootScope', '$q', '$http', '$timeout', 'TimeCounter', 'Auth', 'FormFields',
function ($rootScope, $q, $http, $timeout, TimeCounter, Auth, FormFields) {
return {
templateUrl: './modules/forms/views/directiveViews/form/edit-form.client.view.html',
restrict: 'E',
scope: {
myform:'=',
},
// transclude: true,
controller: function($scope){
/*
@ -17,7 +15,7 @@ angular.module('forms')
*/
//Populate AddField with all available form field types
$scope.addField = {};
$scope.addField.types = FormFields.fields;
$scope.addField.types = FormFields.types;
$scope.addField.types.forEach(function(type){
type.lastAddedID = 1;
@ -76,7 +74,7 @@ angular.module('forms')
// // console.log('has class .dropzone :'+);
// // if ($(e.target).hasClass('dropzone') && ui.item.sortable.droptarget && e.target != ui.item.sortable.droptarget[0] ) {
// // // restore original types
// // $scope.addField.types = FormFields.fields;
// // $scope.addField.types = FormFields.types;
// // }
@ -88,7 +86,7 @@ angular.module('forms')
** Field CRUD Methods
*/
// Add a new field
$scope.addNewField = function(addOrReturn, fieldType){
$scope.addNewField = function(modifyForm, fieldType){
// incr field_id counter
$scope.addField.lastAddedID++;
@ -104,25 +102,21 @@ angular.module('forms')
}
}
var newField = {
'title' : fieldTitle,
'fieldType' : fieldType,
'fieldValue' : '',
'required' : true,
'disabled' : false,
title: fieldTitle,
fieldType: fieldType,
fieldValue: '',
required: true,
disabled: false,
deletePreserved: false
};
console.log('\n\n---------\nAdded field CLIENT');
console.log(newField);
// put newField into fields array
if(addOrReturn){
if(modifyForm){
$scope.myform.form_fields.push(newField);
}else {
return newField;
}
// console.log(Date.now());
// console.log($scope.myform.form_fields.length);
return newField;
};
// deletes particular field on button click
@ -144,7 +138,6 @@ angular.module('forms')
//Insert field at selected index
$scope.myform.form_fields.splice(field_index+1, 0, field);
};
@ -168,7 +161,7 @@ angular.module('forms')
var hashKey = _.chain(button.$$hashKey).words().last().parseInt().value();
for(var i = 0; i < $scope.myform.startPage.buttons.length; i++){
var currHashKey = _.chain($scope.myform.startPage.buttons[i].$$hashKey).words().last().parseInt().value();;
var currHashKey = _.chain($scope.myform.startPage.buttons[i].$$hashKey).words().last().parseInt().value();
if(currHashKey === hashKey){
$scope.myform.startPage.buttons.splice(i, 1);

View file

@ -1,9 +1,9 @@
'use strict';
angular.module('forms').directive('submissionsFormDirective', ['$rootScope', '$http', 'Upload', '$timeout', 'timeCounter', 'Auth', 'FormFields',
function ($rootScope, $http, Upload, $timeout, timeCounter, Auth, FormFields) {
angular.module('forms').directive('editSubmissionsFormDirective', ['$rootScope', '$http', 'Upload', '$timeout', 'TimeCounter', 'Auth', 'FormFields',
function ($rootScope, $http, Upload, $timeout, TimeCounter, Auth, FormFields) {
return {
templateUrl: './modules/forms/views/directiveViews/form/submissions-form.client.view.html',
templateUrl: './modules/forms/views/directiveViews/form/edit-submissions-form.client.view.html',
restrict: 'E',
scope: {
myform:'=',

View file

@ -5,6 +5,8 @@ angular.module('forms').directive('onFinishRender', function ($rootScope, $timeo
restrict: 'A',
link: function (scope, element, attrs) {
// $rootScope.$broadcast(' Started');
//Don't do anything if we don't have a ng-repeat on the current element
if(!element.attr('ng-repeat')){
return;
@ -12,17 +14,19 @@ angular.module('forms').directive('onFinishRender', function ($rootScope, $timeo
var broadcastMessage = attrs.onFinishRender || 'ngRepeat';
if(!scope.$last) {
$timeout(function () {
// console.log(broadcastMessage+'Started');
$rootScope.$broadcast(broadcastMessage+'Started');
if(scope.$first) {
scope.$evalAsync(function () {
// console.log(broadcastMessage+' Started');
// console.log(Date.now());
$rootScope.$broadcast(broadcastMessage+' Started');
});
}else if(scope.$last) {
$timeout(function () {
element.ready(function () {
scope.$evalAsync(function () {
// element.ready(function () {
// console.log(broadcastMessage+'Finished');
$rootScope.$broadcast(broadcastMessage+'Finished');
});
// console.log(Date.now());
$rootScope.$broadcast(broadcastMessage+' Finished');
// });
});
}
}

View file

@ -1,7 +1,7 @@
'use strict';
angular.module('forms').directive('formDirective', ['$http', '$timeout', 'timeCounter', 'Auth', '$filter', '$rootScope',
function ($http, $timeout, timeCounter, Auth, $filter, $rootScope) {
angular.module('forms').directive('formDirective', ['$http', '$timeout', 'TimeCounter', 'Auth', '$filter', '$rootScope',
function ($http, $timeout, TimeCounter, Auth, $filter, $rootScope) {
return {
templateUrl: './modules/forms/views/directiveViews/form/submit-form.client.view.html',
restrict: 'E',
@ -12,7 +12,7 @@ angular.module('forms').directive('formDirective', ['$http', '$timeout', 'timeCo
angular.element(document).ready(function() {
$scope.selected = null;
timeCounter.startClock()
TimeCounter.startClock()
$rootScope.setActiveField = function (field_id) {
console.log('form field clicked: '+field_id);
@ -25,7 +25,7 @@ angular.module('forms').directive('formDirective', ['$http', '$timeout', 'timeCo
};
$scope.submit = function(){
var _timeElapsed = timeCounter.stopClock();
var _timeElapsed = TimeCounter.stopClock();
$scope.form.timeElapsed = _timeElapsed;
// console.log('percentageComplete: '+$filter('formValidity')($scope.form)/$scope.form.visible_form_fields.length*100+'%');
@ -53,8 +53,8 @@ angular.module('forms').directive('formDirective', ['$http', '$timeout', 'timeCo
};
$scope.reloadForm = function(){
timeCounter.stopClock();
timeCounter.startClock();
TimeCounter.stopClock();
TimeCounter.startClock();
$scope.form.submitted = false;
$scope.form.form_fields = _.chain($scope.form.form_fields).map(function(field){
field.fieldValue = '';

View file

@ -1,34 +0,0 @@
'use strict';
angular.module('forms').directive('tableDirective', ['$http', '$timeout', 'Auth',
function ($http, $timeout, Auth) {
return {
templateUrl: './modules/forms/views/directiveViews/table/table.html',
restrict: 'E',
scope: {
rows:'=',
extras:'=',
},
controller: function($scope){
$scope.toggleChecker = function(checked) {
var rows = $scope.gridOptions.$gridScope.renderedRows,
allChecked = true;
for (var r = 0; r < rows.length; r++) {
if (rows[r].entity.checker !== true) {
allChecked = false;
break;
}
}
$scope.gridOptions.$gridScope.checker = allChecked;
};
},
};
}
]);

View file

@ -2,7 +2,7 @@
angular.module('forms').service('FormFields', [
function() {
this.fields = [
this.types = [
{
name : 'textfield',
value : 'Short Text'

View file

@ -1,6 +1,6 @@
'use strict';
angular.module('forms').service('timeCounter', [
angular.module('forms').service('TimeCounter', [
function(){
var _startTime, _endTime, that=this;

View file

@ -2,7 +2,7 @@
(function() {
// Forms Controller Spec
describe('AdminFormController Tests', function() {
describe('AdminForm Controller Tests', function() {
// Initialize global variables
var AdminFormController,
createAdminFormController,
@ -28,9 +28,9 @@
admin: 'ed873933b1f1dea0ce12fab9',
language: 'english',
form_fields: [
{'fieldType':'textfield', 'title':'First Name', 'fieldValue': '', 'deletePreserved': false},
{'fieldType':'checkbox', 'title':'nascar', 'fieldValue': '', 'deletePreserved': false},
{'fieldType':'checkbox', 'title':'hockey', 'fieldValue': '', 'deletePreserved': false}
{fieldType:'textfield', title:'First Name', fieldValue: '', deletePreserved: false},
{fieldType:'checkbox', title:'nascar', fieldValue: '', deletePreserved: false},
{fieldType:'checkbox', title:'hockey', fieldValue: '', deletePreserved: false}
],
_id: '525a8422f6d0f87f0e407a33'
};
@ -40,14 +40,14 @@
admin: 'ed873933b1f1dea0ce12fab9',
language: 'english',
form_fields: [
{'fieldType':'textfield', 'title':'First Name', 'fieldValue': '', 'deletePreserved': false},
{'fieldType':'checkbox', 'title':'nascar', 'fieldValue': '', 'deletePreserved': false},
{'fieldType':'checkbox', 'title':'hockey', 'fieldValue': '', 'deletePreserved': false}
{fieldType:'textfield', title:'First Name', fieldValue: '', deletePreserved: false},
{fieldType:'checkbox', title:'nascar', fieldValue: '', deletePreserved: false},
{fieldType:'checkbox', title:'hockey', fieldValue: '', deletePreserved: false}
],
visible_form_fields: [
{'fieldType':'textfield', 'title':'First Name', 'fieldValue': '', 'deletePreserved': false},
{'fieldType':'checkbox', 'title':'nascar', 'fieldValue': '', 'deletePreserved': false},
{'fieldType':'checkbox', 'title':'hockey', 'fieldValue': '', 'deletePreserved': false}
{fieldType:'textfield', title:'First Name', fieldValue: '', deletePreserved: false},
{fieldType:'checkbox', title:'nascar', fieldValue: '', deletePreserved: false},
{fieldType:'checkbox', title:'hockey', fieldValue: '', deletePreserved: false}
],
_id: '525a8422f6d0f87f0e407a33'
};
@ -70,7 +70,7 @@
this.opened = false;
this.cancelCallback( type );
};
}
};
@ -93,6 +93,12 @@
});
});
// Load the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
beforeEach(module('stateMock'));
//Mock Users Service
beforeEach(module(function($provide) {
$provide.service('User', function($q) {
@ -148,10 +154,6 @@
});
}));
// Load the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
beforeEach(module('stateMock'));
beforeEach(inject(function($modal) {
spyOn($modal, 'open').and.returnValue(new fakeModal());
@ -224,14 +226,15 @@
scope.openDeleteModal();
scope.deleteModal.result(function(selectedItem){
scope.selected = selectedItem;
this.selected = selectedItem;
}, function(type){
$scope.canceled = true;
this.canceled = true;
});
scope.removeCurrentForm();
$httpBackend.flush();
$state.ensureAllTransitionsHappened();
});
it('$scope.update() should send a PUT request with the id of form', function() {
@ -267,8 +270,8 @@
this.canceled = true;
});
//Run controller functionality
scope.cancelDeleteModal();
console.log(scope.deleteModal.opened);
expect( scope.deleteModal.opened ).toEqual(false);
expect( scope.deleteModal.canceled ).toEqual(true);

View file

@ -0,0 +1,137 @@
'use strict';
(function() {
// Forms Controller Spec
describe('configureForm Tests', function() {
// Initialize global variables
var el, scope, controller, $httpBackend;
var sampleUser = {
firstName: 'Full',
lastName: 'Name',
email: 'test@test.com',
username: 'test@test.com',
password: 'password',
provider: 'local',
roles: ['user'],
_id: 'ed873933b1f1dea0ce12fab9',
};
var pdfObj = {
fieldname:"file",
originalname:"test.pdf",
name:"1440112660375.pdf",
encoding:"7bit",
mimetype:"application/pdf",
path:"uploads/tmp/test@test.com/1440112660375.pdf",
extension:"pdf",
size:56223,
truncated:false,
buffer:null
};
var sampleForm = {
title: 'Form Title',
admin: 'ed873933b1f1dea0ce12fab9',
language: 'english',
form_fields: [
{fieldType:'textfield', title:'First Name', fieldValue: '', deletePreserved: false},
{fieldType:'checkbox', title:'nascar', fieldValue: '', deletePreserved: false},
{fieldType:'checkbox', title:'hockey', fieldValue: '', deletePreserved: false}
],
pdf: {},
pdfFieldMap: {},
startPage: {
showStart: false
},
hideFooter: false,
isGenerated: false,
isLive: false,
autofillPDFs: false,
_id: '525a8422f6d0f87f0e407a33',
};
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function() {
jasmine.addMatchers({
toEqualData: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Load the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
beforeEach(module('stateMock'));
beforeEach(module('module-templates'));
beforeEach(inject(function($compile, $controller, $rootScope, _$httpBackend_) {
//Instantiate directive.
var tmp_scope = $rootScope.$new();
tmp_scope.myform = sampleForm;
tmp_scope.user = sampleUser;
//gotacha: Controller and link functions will execute.
el = angular.element('<configure-form-directive myform="myform" user="user"></configure-form-directive>');
$compile(el)(tmp_scope);
$rootScope.$digest();
// Point global variables to injected services
$httpBackend = _$httpBackend_;
// $httpBackend.whenGET(/.+\.html$/).respond('');
$httpBackend.whenGET('/users/me/').respond('');
//Grab controller instance
controller = el.controller();
//Grab scope. Depends on type of scope.
//See angular.element documentation.
scope = el.isolateScope() || el.scope();
// spyOn(scope, 'update');
// spyOn(scope, 'resetForm');
}));
it('$scope.uploadPDF() should upload a pdf file', function() {
// expect(scope.isInitialized).toBeDefined()
// expect(scope.log).toEqual('');
expect(scope.pdfLoading).toBe(false);
//Set POST response
$httpBackend.when('POST', '/upload/pdf').respond(pdfObj);
var files = [{}];
scope.uploadPDF(files);
$httpBackend.flush();
expect(scope.myform.pdf).toEqualData(pdfObj);
});
it('$scope.removePDF() should removed uploaded pdf file', function() {
// expect(scope.isInitialized).toBeDefined()
// expect(scope.log).toEqual('');
scope.myform.pdf = pdfObj;
scope.myform.isGenerated = true;
scope.myform.autofillPDFs = true;
scope.removePDF();
expect(scope.myform.pdf).toEqual(null);
expect(scope.myform.isGenerated).toBe(false);
expect(scope.myform.autofillPDFs).toBe(false);
});
});
}());

View file

@ -0,0 +1,126 @@
'use strict';
(function() {
// Forms Controller Spec
describe('editForm Tests', function() {
// Initialize global variables
var el, scope, controller, $httpBackend;
var sampleUser = {
firstName: 'Full',
lastName: 'Name',
email: 'test@test.com',
username: 'test@test.com',
password: 'password',
provider: 'local',
roles: ['user'],
_id: 'ed873933b1f1dea0ce12fab9',
};
var pdfObj = {
fieldname:"file",
originalname:"test.pdf",
name:"1440112660375.pdf",
encoding:"7bit",
mimetype:"application/pdf",
path:"uploads/tmp/test@test.com/1440112660375.pdf",
extension:"pdf",
size:56223,
truncated:false,
buffer:null
};
var sampleForm = {
title: 'Form Title',
admin: 'ed873933b1f1dea0ce12fab9',
language: 'english',
form_fields: [
{fieldType:'textfield', title:'First Name', fieldValue: '', required: true, disabled: false, deletePreserved: false},
{fieldType:'checkbox', title:'nascar', fieldValue: '', required: true, disabled: false, deletePreserved: false},
{fieldType:'checkbox', title:'hockey', fieldValue: '', required: true, disabled: false, deletePreserved: false}
],
pdf: {},
pdfFieldMap: {},
startPage: {
showStart: false
},
hideFooter: false,
isGenerated: false,
isLive: false,
autofillPDFs: false,
_id: '525a8422f6d0f87f0e407a33',
};
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function() {
jasmine.addMatchers({
toEqualData: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Load the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
beforeEach(module('stateMock'));
beforeEach(module('module-templates'));
beforeEach(inject(function($compile, $controller, $rootScope, _$httpBackend_) {
//Instantiate directive.
var tmp_scope = $rootScope.$new();
tmp_scope.myform = sampleForm;
//gotacha: Controller and link functions will execute.
el = angular.element('<edit-form-directive myform="myform"></edit-form-directive>');
$compile(el)(tmp_scope);
$rootScope.$digest();
// Point global variables to injected services
$httpBackend = _$httpBackend_;
// $httpBackend.whenGET(/.+\.html$/).respond('');
$httpBackend.whenGET('/users/me/').respond('');
//Grab controller instance
controller = el.controller();
//Grab scope. Depends on type of scope.
//See angular.element documentation.
scope = el.isolateScope() || el.scope();
}));
it('$scope.addNewField() should ADD a new field to $scope.myform.form_fields', function() {
scope.addNewField(true, 'textfield');
var sampleFormField = {
fieldType:'checkbox',
title:'hockey',
fieldValue: '',
required: true,
disabled: false,
deletePreserved: false
};
expect(scope.myform.form_fields.length).toEqual(sampleForm.form_fields.length+1);
expect(_.last(scope.myform.form_fields)).toEqualData(sampleFormField);
});
it('$scope.deleteField() should DELETE a field to $scope.myform.form_fields', function() {
scope.deleteField(scope.myform.form_fields[0].$$hashKey);
expect(scope.myform.form_fields.length).toEqual(sampleForm.form_fields.length-1);
expect(_.first(scope.myform.form_fields)).toEqualData(sampleForm.form_fields[1]);
});
});
}());

View file

@ -0,0 +1,54 @@
'use strict';
(function() {
// Forms Controller Spec
describe('FieldIcon Directive Tests', function() {
// Initialize global variables
var scope,
FormFields,
faClasses = {
'textfield': 'fa fa-pencil-square-o',
'dropdown': 'fa fa-th-list',
'date': 'fa fa-calendar',
'checkbox': 'fa fa-check-square-o',
'radio': 'fa fa-dot-circle-o',
'email': 'fa fa-envelope-o',
'textarea': 'fa fa-pencil-square',
'legal': 'fa fa-legal',
'file': 'fa fa-cloud-upload',
'rating': 'fa fa-star-half-o',
'link': 'fa fa-link',
'scale': 'fa fa-sliders',
'stripe': 'fa fa-credit-card',
'statement': 'fa fa-quote-left',
'yes_no': 'fa fa-toggle-on',
'number': 'fa fa-slack'
};
// Load the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
beforeEach(inject(function ($rootScope, _FormFields_) {
scope = $rootScope.$new();
FormFields = _FormFields_;
}));
it('should be able render all field-icon types', inject(function($compile) {
var currType,
currClass;
for(var i=0; i<FormFields.types.length; i++){
currType = FormFields.types[i];
currClass = faClasses[currType.name];
var element = $compile('<field-icon-directive type-name="'+currType.name+'"></field-icon-directive>')(scope);
scope.$digest();
expect(currClass).toBeDefined();
expect(element.find('i')).not.toBe(null);
expect(element.find('i').hasClass(currClass)).toBe(true);
}
}));
});
}());

View file

@ -0,0 +1,47 @@
'use strict';
(function() {
// Forms Controller Spec
describe('onFinishRender Directive Tests', function() {
// Initialize global variables
var scope,
FormFields;
// Load the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
beforeEach(inject(function ($rootScope, _FormFields_) {
scope = $rootScope.$new();
FormFields = _FormFields_;
spyOn($rootScope, '$broadcast');
}));
it('should emit Custom "Finished" and "Started" events on ng-repeat', inject(function($compile, $rootScope) {
// console.log(FormFields.types);
scope.myfields = FormFields.types;
var e = $compile('<div><div ng-repeat="item in myfields" on-finish-render="editFormFields">{{item.name}}</div></div>')(scope);
scope.$digest();
//run code to test
expect($rootScope.$broadcast).toHaveBeenCalledWith('editFormFields Started');
expect(scope.$broadcast).toHaveBeenCalledWith('editFormFields Finished');
}));
it('should emit "ngRepeat Finished" and "ngRepeat Started" events on ng-repeat when attr is not set to string', inject(function($compile, $rootScope) {
// console.log(FormFields.types);
scope.myfields = FormFields.types;
var e = $compile('<div><div ng-repeat="item in myfields" on-finish-render>{{item.name}}</div></div>')(scope);
scope.$digest();
//run code to test
expect($rootScope.$broadcast).toHaveBeenCalledWith('ngRepeat Started');
expect(scope.$broadcast).toHaveBeenCalledWith('ngRepeat Finished');
}));
});
}());

View file

@ -1,91 +0,0 @@
// 'use strict';
// (function() {
// // Forms Controller Spec
// describe('SubmissionsFormDirective Tests', function() {
// // Initialize global variables
// var SubmissionsFormDirective,
// scope,
// $httpBackend,
// $stateParams,
// $location;
// // The $resource service augments the response object with methods for updating and deleting the resource.
// // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// // When the toEqualData matcher compares two objects, it takes only object properties into
// // account and ignores methods.
// beforeEach(function() {
// jasmine.addMatchers({
// toEqualData: function(util, customEqualityTesters) {
// return {
// compare: function(actual, expected) {
// return {
// pass: angular.equals(actual, expected)
// };
// }
// };
// }
// });
// });
// // Then we can start by loading the main application module
// beforeEach(module(ApplicationConfiguration.applicationModuleName));
// // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// // This allows us to inject a service but then attach it to a variable
// // with the same name as the service.
// beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
// // Set a new global scope
// scope = $rootScope.$new();
// // Point global variables to injected services
// $stateParams = _$stateParams_;
// $httpBackend = _$httpBackend_;
// $location = _$location_;
// // Initialize the Forms controller.
// FormsController = $controller('AdminFormsController', {
// $scope: scope
// });
// }));
// function compileDirective(tpl) {
// // function to compile a fresh directive with the given template, or a default one
// // compile the tpl with the $rootScope created above
// // wrap our directive inside a form to be able to test
// // that our form integration works well (via ngModelController)
// // our directive instance is then put in the global 'elm' variable for further tests
// if (!tpl) tpl = '<div rn-stepper ng-model="testModel"></div></form>';
// tpl = '<form name="form">' + tpl + '</tpl>';
// // inject allows you to use AngularJS dependency injection
// // to retrieve and use other services
// inject(function($compile) {
// var form = $compile(tpl)(scope);
// elm = form.find('div');
// });
// // $digest is necessary to finalize the directive generation
// scope.$digest();
// }
// describe('initialisation', function() {
// // before each test in this block, generates a fresh directive
// beforeEach(function() {
// compileDirective();
// });
// // a single test example, check the produced DOM
// it('should produce 2 buttons and a div', function() {
// expect(elm.find('button').length).toEqual(2);
// expect(elm.find('div').length).toEqual(1);
// });
// it('should check validity on init', function() {
// expect(scope.form.$valid).toBeTruthy();
// });
// });
// it('$scope.find() should create an array with at least one article object fetched from XHR', inject(function(Forms) {
// }));
// });
// }());

View file

@ -2,7 +2,7 @@
(function() {
// Forms Controller Spec
describe('ListFormsController Tests', function() {
describe('ListForms Controller Tests', function() {
// Initialize global variables
var ListFormsController,
createListFormsController,
@ -12,25 +12,14 @@
$location,
$state;
var sampleUser = {
firstName: 'Full',
lastName: 'Name',
email: 'test@test.com',
username: 'test@test.com',
password: 'password',
provider: 'local',
roles: ['user'],
_id: 'ed873933b1f1dea0ce12fab9'
};
var sampleForm = {
title: 'Form Title',
admin: 'ed873933b1f1dea0ce12fab9',
language: 'english',
form_fields: [
{'fieldType':'textfield', 'title':'First Name', 'fieldValue': '', 'deletePreserved': false},
{'fieldType':'checkbox', 'title':'nascar', 'fieldValue': '', 'deletePreserved': false},
{'fieldType':'checkbox', 'title':'hockey', 'fieldValue': '', 'deletePreserved': false}
{fieldType:'textfield', title:'First Name', fieldValue: '', deletePreserved: false},
{fieldType:'checkbox', title:'nascar', fieldValue: '', deletePreserved: false},
{fieldType:'checkbox', title:'hockey', fieldValue: '', deletePreserved: false}
],
_id: '525a8422f6d0f87f0e407a33'
};
@ -40,9 +29,9 @@
admin: 'ed873933b1f1dea0ce12fab9',
language: 'english',
form_fields: [
{'fieldType':'textfield', 'title':'First Name', 'fieldValue': '', 'deletePreserved': false},
{'fieldType':'checkbox', 'title':'nascar', 'fieldValue': '', 'deletePreserved': false},
{'fieldType':'checkbox', 'title':'hockey', 'fieldValue': '', 'deletePreserved': false}
{fieldType:'textfield', title:'First Name', fieldValue: '', deletePreserved: false},
{fieldType:'checkbox', title:'nascar', fieldValue: '', deletePreserved: false},
{fieldType:'checkbox', title:'hockey', fieldValue: '', deletePreserved: false}
],
_id: '525a8422f6d0f87f0e407a33'
},{
@ -50,9 +39,9 @@
admin: '39223933b1f1dea0ce12fab9',
language: 'english',
form_fields: [
{'fieldType':'textfield', 'title':'First Name', 'fieldValue': '', 'deletePreserved': false},
{'fieldType':'checkbox', 'title':'nascar', 'fieldValue': '', 'deletePreserved': false},
{'fieldType':'checkbox', 'title':'hockey', 'fieldValue': '', 'deletePreserved': false}
{fieldType:'textfield', title:'First Name', fieldValue: '', deletePreserved: false},
{fieldType:'checkbox', title:'nascar', fieldValue: '', deletePreserved: false},
{fieldType:'checkbox', title:'hockey', fieldValue: '', deletePreserved: false}
],
_id: '52f6d0f87f5a407a384220e3'
},{
@ -60,9 +49,9 @@
admin: '2fab9ed873937f0e1dea0ce1',
language: 'english',
form_fields: [
{'fieldType':'textfield', 'title':'First Name', 'fieldValue': '', 'deletePreserved': false},
{'fieldType':'checkbox', 'title':'nascar', 'fieldValue': '', 'deletePreserved': false},
{'fieldType':'checkbox', 'title':'hockey', 'fieldValue': '', 'deletePreserved': false}
{fieldType:'textfield', title:'First Name', fieldValue: '', deletePreserved: false},
{fieldType:'checkbox', title:'nascar', fieldValue: '', deletePreserved: false},
{fieldType:'checkbox', title:'hockey', fieldValue: '', deletePreserved: false}
],
_id: '922f6d0f87fed8730e4e1233'
}
@ -87,62 +76,7 @@
}
});
});
//Mock Users Service
beforeEach(module(function($provide) {
$provide.service('User', function($q) {
return {
getCurrent: function() {
var deferred = $q.defer();
deferred.resolve( JSON.stringify(sampleUser) );
return deferred.promise;
},
login: function(credentials) {
var deferred = $q.defer();
if( credentials.password === sampleUser.password && credentials.username === sampleUser.username){
deferred.resolve( JSON.stringify(sampleUser) );
}else {
deferred.resolve('Error: User could not be loggedin');
}
return deferred.promise;
},
logout: function() {
var deferred = $q.defer();
deferred.resolve(null);
return deferred.promise;
},
signup: function(credentials) {
var deferred = $q.defer();
if( credentials.password === sampleUser.password && credentials.username === sampleUser.username){
deferred.resolve( JSON.stringify(sampleUser) );
}else {
deferred.resolve('Error: User could not be signed up');
}
return deferred.promise;
}
};
});
}));
//Mock Authentication Service
beforeEach(module(function($provide) {
$provide.service('Auth', function() {
return {
ensureHasCurrentUser: function() {
return sampleUser;
},
isAuthenticated: function() {
return true;
},
getUserState: function() {
return true;
}
};
});
}));
// Load the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
@ -264,7 +198,7 @@
},
$dirty: true,
$valid: true,
}
};
// scope.forms.createForm.language.$modelValue = 'english';
// scope.forms.createForm.name.$modelValue = 'Test Form5';
// scope.forms.createForm.$dirty = true;
@ -279,6 +213,7 @@
scope.createNew();
$httpBackend.flush();
$state.ensureAllTransitionsHappened();
}));
});

View file

@ -0,0 +1,54 @@
'use strict';
(function() {
// Forms Controller Spec
describe('CurrentForm Service Tests', function() {
// Initialize global variables
var CurrentForm,
sampleForm = {
title: 'Form Title',
admin: 'ed873933b1f1dea0ce12fab9',
language: 'english',
form_fields: [
{'fieldType':'textfield', 'title':'First Name', 'fieldValue': '', 'deletePreserved': false},
{'fieldType':'checkbox', 'title':'nascar', 'fieldValue': '', 'deletePreserved': false},
{'fieldType':'checkbox', 'title':'hockey', 'fieldValue': '', 'deletePreserved': false}
],
_id: '525a8422f6d0f87f0e407a33'
};
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function() {
jasmine.addMatchers({
toEqualData: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Load the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
beforeEach(inject(function (_CurrentForm_) {
CurrentForm = _CurrentForm_;
}));
it('CurrentForm be able to get() and set() a Form', function() {
CurrentForm.setForm(sampleForm);
var newForm = CurrentForm.getForm();
expect(sampleForm).toEqualData(newForm);
});
});
}());

View file

@ -0,0 +1,28 @@
'use strict';
(function() {
// Forms Controller Spec
describe('TimeCounter Service Tests', function() {
// Initialize global variables
var TimeCounter;
// Load the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
beforeEach(inject(function (_TimeCounter_) {
TimeCounter = _TimeCounter_;
}));
it('should be able to time 1 second interval as 1 second', function() {
var timeSpent = 0;
TimeCounter.startClock();
setTimeout(function(){
timeSpent = TimeCounter.stopClock();
expect(timeSpent).toEqual(1);
},1000);
});
});
}());

View file

@ -0,0 +1,228 @@
'use strict';
(function() {
// Forms Controller Spec
describe('SubmitForm Controller Tests', function() {
// Initialize global variables
var SubmitFormController,
createSubmitFormController,
scope,
$httpBackend,
$stateParams,
$location,
$state;
var sampleUser = {
firstName: 'Full',
lastName: 'Name',
email: 'test@test.com',
username: 'test@test.com',
password: 'password',
provider: 'local',
roles: ['user'],
_id: 'ed873933b1f1dea0ce12fab9'
};
var sampleForm = {
title: 'Form Title',
admin: 'ed873933b1f1dea0ce12fab9',
language: 'english',
form_fields: [
{'fieldType':'textfield', 'title':'First Name', 'fieldValue': '', 'deletePreserved': false},
{'fieldType':'checkbox', 'title':'nascar', 'fieldValue': '', 'deletePreserved': false},
{'fieldType':'checkbox', 'title':'hockey', 'fieldValue': '', 'deletePreserved': false}
],
isLive: false,
_id: '525a8422f6d0f87f0e407a33',
visible_form_fields: [
{'fieldType':'textfield', 'title':'First Name', 'fieldValue': '', 'deletePreserved': false},
{'fieldType':'checkbox', 'title':'nascar', 'fieldValue': '', 'deletePreserved': false},
{'fieldType':'checkbox', 'title':'hockey', 'fieldValue': '', 'deletePreserved': false}
],
};
//Mock Users Service
beforeEach(module(function($provide) {
$provide.service('User', function($q) {
return {
getCurrent: function() {
var deferred = $q.defer();
deferred.resolve( JSON.stringify(sampleUser) );
return deferred.promise;
},
login: function(credentials) {
var deferred = $q.defer();
if( credentials.password === sampleUser.password && credentials.username === sampleUser.username){
deferred.resolve( JSON.stringify(sampleUser) );
}else {
deferred.resolve('Error: User could not be loggedin');
}
return deferred.promise;
},
logout: function() {
var deferred = $q.defer();
deferred.resolve(null);
return deferred.promise;
},
signup: function(credentials) {
var deferred = $q.defer();
if( credentials.password === sampleUser.password && credentials.username === sampleUser.username){
deferred.resolve( JSON.stringify(sampleUser) );
}else {
deferred.resolve('Error: User could not be signed up');
}
return deferred.promise;
}
};
});
}));
//Mock Authentication Service
beforeEach(module(function($provide) {
$provide.service('Auth', function() {
return {
ensureHasCurrentUser: function() {
return sampleUser;
},
isAuthenticated: function() {
return true;
},
getUserState: function() {
return true;
}
};
});
}));
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function() {
jasmine.addMatchers({
toEqualData: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Load the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
beforeEach(module('stateMock'));
//Mock Authentication Service
beforeEach(module(function($provide) {
$provide.service('Auth', function() {
return {
ensureHasCurrentUser: function() {
return sampleUser;
},
isAuthenticated: function() {
return true;
},
getUserState: function() {
return true;
}
};
});
}));
//Mock Users Service
beforeEach(module(function($provide) {
$provide.service('User', function($q) {
return {
getCurrent: function() {
var deferred = $q.defer();
deferred.resolve( JSON.stringify(sampleUser) );
return deferred.promise;
},
login: function(credentials) {
var deferred = $q.defer();
if( credentials.password === sampleUser.password && credentials.username === sampleUser.username){
deferred.resolve( JSON.stringify(sampleUser) );
}else {
deferred.resolve('Error: User could not be loggedin');
}
return deferred.promise;
},
logout: function() {
var deferred = $q.defer();
deferred.resolve(null);
return deferred.promise;
},
signup: function(credentials) {
var deferred = $q.defer();
if( credentials.password === sampleUser.password && credentials.username === sampleUser.username){
deferred.resolve( JSON.stringify(sampleUser) );
}else {
deferred.resolve('Error: User could not be signed up');
}
return deferred.promise;
}
};
});
}));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function($controller, $rootScope, _$state_, _$location_, _$stateParams_, _$httpBackend_, CurrentForm, Forms) {
// Set a new global scope
scope = $rootScope.$new();
//Set CurrentForm
CurrentForm.setForm(sampleForm);
// Point global variables to injected services
$stateParams = _$stateParams_;
$httpBackend = _$httpBackend_;
$location = _$location_;
$state = _$state_;
$httpBackend.whenGET(/\.html$/).respond('');
$httpBackend.whenGET('/users/me/').respond('');
// Initialize the Forms controller.
createSubmitFormController = function(){
return $controller('SubmitFormController', { $scope: scope });
};
}));
it('$scope.initForm() should populate $scope.myform with current Form', inject(function(Forms) {
var controller = createSubmitFormController();
$stateParams.formId = '525a8422f6d0f87f0e407a33';
// Set GET response
$httpBackend.expectGET(/^(\/forms\/)([0-9a-fA-F]{24})$/).respond(200, sampleForm);
// Run controller functionality
scope.initForm();
$httpBackend.flush();
$state.ensureAllTransitionsHappened();
// Test scope value
expect( scope.myform.toJSON() ).toEqualData(sampleForm);
expect( scope.hideNav ).toEqual(false);
}));
});
}());

View file

@ -1,4 +1,4 @@
<section data-ng-controller="SubmitFormController" class="public-form">
<section data-ng-controller="SubmitFormController" class="public-form" ng-init="initForm()">
<form-directive form="myform"></form-directive>