How do I trigger a click event in a unit test for an Angular directive - asp.net-mvc

I have an Angular app (running from an ASP.NET MVC project.)
In this app, I have a directive with the following link function:
link: function (scope, element, attrs, formCtrl) {
element.bind('click', function (event) {
formCtrl.$setPristine();
});
}
I wrote this test:
var $compile,
$rootScope,
form;
beforeEach(module('points'));
beforeEach(inject(function(_$compile_, _$rootScope_, testHelper){
$compile = _$compile_;
$rootScope = _$rootScope_;
testHelper.expectBaseRoute();
}));
it('Should set form to pristine when clicked', function () {
var scope = $rootScope;
form = $compile('<form name="testForm" unsaved-warning-clear><input name="test" ng-model="value"/></form>')(scope);
scope.value = "abc";
scope.$digest();
scope.testForm.test.$setViewValue('def');
expect(scope.testForm.$pristine).toBe(false);
$(form).trigger('click');
expect(scope.testForm.$pristine).toBe(true);
});
If I run that in the browser using Jasmine, the test passes.
If I run it with chutzpah inside the ide, it fails. It never fires the click event.
Is there something I'm missing?

For my case, it was an incident of stupid user error.
My Jasmine test runner file being run from the browser had jquery, then angular referenced.
My chutzpah.json file had it the inverse order.
I moved the jquery reference up and it started working.

Related

Trying to get angular mock to work with teaspoon-jasmine

So i'm working in ruby on rails, and I've using it with AngularJS 1 for the first time, and therefore am setting up the unit testing for angularjs inside rails for the first time. I can test rails with rspec no problem, but i've been struggling to test angularjs, currently I'm working with teaspoon-jasmine and angular-mocks to test a simple angular controller, but I run into several problems. The first file below is my test file, I currently have it using angular.mock.module/inject and the error i'm getting is "Failed to instantiate module angularrApp due to..." it's basically saying I haven't created or loaded angularApp anywhere, I though mock was supposed to create a test module? If I the module to "angular.module("name", [])" like I would normally create an angular app, I run into more problems such as the mainController hasn't been created. I'm just overall having issues getting this to work properly, any suggestions? I'm trying to get just the simple first expect to work before I move on to the actual tests. And I am requiring angular and angular-mocks in the spec_helper.js file, all the files below. Would it help to require the file that creates the angular app in my spec_helper.js? I've tried but can't get it to work since one is in the spec directory, while my angular app is in app/assets. Also if it helps, here is the link to the tutorial I based this code off of http://angular-rails.com/find_and_browse.html
mainController_spec.js (test file)
'use strict';
describe("mainController", function() {
var scope,
ctrl,
location,
resource;
var setupController = function() {
angular.mock.inject( function($rootScope, $resource, $controller) {
scope = $rootScope.$new();
resource = $resource;
ctrl = $controller('mainController', {$scope: scope, $resource: resource });
})
}
beforeEach(function(){
angular.mock.module("angularApp");
setupController();
})
it('should work', function(){
expect(true).toBe(true);
// expect(scope.games).toBe([])
})
});
mainController.js
'use strict';
myApp.controller('mainController', [ 'mainFactory', '$scope', '$resource', (factory, scope, resource) => {
scope.games = [];
factory.populateTable((data) => {
scope.games = data;
})
}]);
angular-app.js
'use strict';
const myApp = angular.module('angularApp', ['ngRoute', 'ngResource']);
// routes in another file
For those that are interested, the issue I was having was that either teaspoon-jasmine, phantomjs or both don't recognize javascript es6 syntax, if there is any es6 in a file that would normally be required, the entire file and it's contents are ignored without any error messages. Once I reverted my angularApp and controller code to ES5, my problem was solved.

how to use a jquery plugin in an asp.net mvc 5 view button click

I am just a newbie to programming so please be gentle.
I am working with Visual Studio Community 2015 edition.
My project uses a standard asp.net MVC 5 solution template.
I have a visual studio scaffolded input form that includes a create button.
I am having a problem trying to stop multiple submissions of the form due to double clicking.
I have been trying to implement a solution posted on stackoverflow a few years ago but after two days of trying I am no further forward.
The solution involves using the following jquery plugin (I must admit I do not know much about java yet!)
This jquery plugin code I am wanting to use is below and comes from this original post
Prevent double submission of forms in jQuery
jQuery.fn.preventDoubleSubmission = function() {
$('input[type="submit"]').data('loading-text', 'Loading...');
$(this).on('submit',function(e){
var $form = $(this);
$('input[type="submit"]', $form).button('loading');
if ($form.data('submitted') === true) {
// Previously submitted - don't submit again
e.preventDefault();
} else {
// Mark it so that the next submit can be ignored
$form.data('submitted', true);
$form.setFormTimeout();
}
});
// Keep chainability
return this;
};
jQuery.fn.setFormTimeout = function() {
var $form = $(this);
setTimeout(function() {
$('input[type="submit"]', $form).button('reset');
alert('Form failed to submit within 30 seconds');
}, 30000);
};
*/
The problem I am having is how to deploy the jquery plugin in my project and then how to call it when someone clicks the create button.
I have tried putting the plugin directly in the page view and also as a javascript file in the scripts folder but still cant seem to call the function to prevent double submissions.
I am trying to call the function by using the onclick property of the button but just cant get it to run. Does anyone have a memory of the previous solution and how to implement it in an ASP.NET MVC 5 cshtml view button click?
(Where do I put the plugin code and how do I call it from the create button)
Many thanks
Use This code in jquery side is prevent double click
$(document).on('submit', 'form', function () {
var button = $(this).find('input[type="submit"]');
setTimeout(function () {
button.attr('disabled', 'disabled');
}, 0);
});
If Not valid post time your form and validation after
//disabled Multiple Click Event on form
$(document).on('invalid-form.validate', 'form', function () {
var button = $(this).find('input[type="submit"]');
setTimeout(function () {
button.removeAttr('disabled');
}, 1);
});

UI not updating on 'pageinit', probably timing issue

I have the following .js file for my project. This is running in a regular browser, using jquery 1.9.x and jquerymobile 1.3.1. The init function below appears to be running when the page loads and the UI is not updated. Though... I can copy the function into the console and run it, and the UI updates as it is supposed to, so this in not a case of incorrect file paths, or incorrect ids for the UI elements, but I suspect timing. I am also NOT using cordova or phone gap in this instance.
So, my question is, why is the UI not updating when the $(document).bind('pageinit', ...) function is called? If I put a breakpoint in the init method, it is getting called when the page loads. Any suggestions on using a different event or approach?
var simulator = simulator || {};
(function (feedback, $, undefined) { 'use-strict';
feedback.init = function () {
$.get('feedback-config.xml', function (data) {
$('#feedback-to').val($(data).find('email').text());
$('#feedback-subject').val($(data).find('emailSubject').text());
$('#feedback-display').html($(data).find('message').text());
$('#feedback-form').attr('action', $(data).find('serverurl').text()).ajaxForm({success: function () {
alert("Thank you for your feedback!");
}, error: function () {
alert("We're having difficulties sending your feedback, sorry for the inconvenience.");
}});
});
};
}(simulator.feedback = simulator.feedback || {}, jQuery));
$(document).bind('pageinit', function () { 'use strict';
simulator.feedback.init;
});
Thanks in advance.
Found it, simple mistake... In the 'pageinit' function I am calling simulator.feedback.init; instead of simulator.feedback.init(); Not sure why JSLint didn't pick that up initially, but it pointed it out when I tried again later. Thanks.

requirejs modules does not catch pageinit event

I am working on an application using jquery mobile and in the process of re-factoring the app into modules with RequireJS. I have almost completed the task but ran into one a problem which I need a little help with.
I am manually loading my script files (jquery, jqm, knockout etc) and define these libraries as the first thin in my main.js file.
(function(){
var root = this
define('jquery', [], function () { return root.jQuery; });
define('ko', [], function () { return root.ko; });
....
})();
Next I load the jquery mobile plugin and boot the application
....
require([
'Scripts/lib/mobile/jquery.mobile-1.2.0'
], function () {
$(document).on('pageinit' function(){ alert('page init event triggere'); });
boot();
});
My problem is that 'pageinit' event is already triggered by the time requirejs executes factory function, which attaches to the event. Subsequent pageinit events are catched as expected but im missing the initial one when the app first loads. If I move the event binding out of the require module it works fine. Any ideas how I register and handle these jqm events?
Thanks in advance.
I had the same problem and I found that you shouldn't load jquery mobile module as a global dependency, but directly in the core of the function :
require(["jquery"], function($) {
console.log("requireJS loaded");
require(["jquery.mobile"]);
$( document ).on( 'pagecreate pageinit pageshow', '#mappage', function( event ) {
var eventType = event.type;
switch(eventType) {
case 'pagecreate':
console.log("mappage : pagecreate");
break;
case 'pageinit':
console.log("mappage : pageinit");
break;
case 'pageshow':
console.log("mappage : pageshow");
break;
};
});
});

Jquery calls not working in $viewContentLoaded of Angular

Unable to call jquery functions in $viewContentLoaded event of Angular controller, here is the code for the same.
$scope.$on('$viewContentLoaded', function() {
jQuery.growlUI('Growl Notification', 'Saved Succesfully');
jQuery('#category').tree()
});
Is any configuration required here?? I tried even noConflict(); var $jq = jQuery.noConflict();
Does it require any other configuration?
Thanks,
Abdul
First thing first, don't do DOM manipulation from controller. Instead do it from directives.
You can do same thing in directive link method. You can access the element on which directive is applied.
Make sure you load jquery before angularjs scripts, then grawlUI, three, angularJS and finally your application script. Below is directive sample
var app = angular.module("someModule", []);
app.directive("myDirective", function () {
return function (scope, element, attrs) {
$.growlUI('Growl Notification', 'Saved Succesfully');
element.tree();
};
});
angularjs has built in jQuery lite.
if you load full jquery after angular, since jQuery is already defined, the full jquery script will skip execution.
==Update after your comment==
I reviewed again your question after comment and realised that content which is loaded trough ajax is appended to some div in your angular view. Then you want to apply element.tree() jquery plugin to that content. Unfortunately example above will not work since it is fired on linking which happened before your content from ajax response is appended to element with directive I showed to you. But don't worry, there is a way :) tho it is quick and dirty but it is just for demo.
Let's say this is your controller
function ContentCtrl($scope, $http){
$scope.trees=[];
$scope.submitSomethingToServer=function(something){
$http.post("/article/1.html", something)
.success(function(response,status){
// don't forget to set correct order of jquery, angular javascript lib load
$.growlUI('Growl Notification', 'Saved Succesfully');
$scope.trees.push(response); // append response, I hope it is HTML
});
}
}
Now, directive which is in controller scope (it uses same scope as controller)
var app = angular.module("someModule", []);
app.directive("myDirective", function () {
return function (scope, element, attrs) {
scope.$watch("trees", function(){
var newParagraph=$("<p>" + scope.trees[scope.trees.length-1] + "</p>" ); // I hope this is ul>li>ul>li...or what ever you want to make as tree
element.append(newParagraph);
newParagraph.tree(); //it will apply tree plugin after content is appended to DOM in view
});
};
});
The second approach would be to $broadcast or $emit event from controller (depends where directive is, out or in scope of controller) after your ajax completes and you get content from server. Then directive should be subscribed to this event and handle it by receiving passed data (data=content as string) and do the rest as I showed you above.
The thing is, threat that content from ajax as data all the way it comes to directive, then inject it to element in which you want to render it and apply tree plugin to that content.

Resources