Skip to content

Instantly share code, notes, and snippets.

@foxyblocks
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foxyblocks/d5e92e6a3e3620b11bd1 to your computer and use it in GitHub Desktop.
Save foxyblocks/d5e92e6a3e3620b11bd1 to your computer and use it in GitHub Desktop.
var angular = require('angular');
// Simple directive that prevents an event from propagating to
// up the dom tree.
//
// ex:
// <div ng-click='doSomething()'>
// <a stop-event='click'>Some link</a>
// </div>
//
// Will prevent the doSomething() from being called when clicking the link
angular
.module('Common')
.directive('stopEvent', function () {
return {
restrict: 'A',
link: function (scope, element, attr) {
element.bind(attr.stopEvent, function (e) {
e.stopPropagation();
});
}
};
});
var angular = require('angular');
describe('stopEvent', function() {
var element,
scope;
// Really long setup for testing an angular directive
//---------------------------------------------------------
beforeEach(function() {
// Here we redefine the common module. This is sort of like a stub so we
// don't have to require the whole module.
angular.module('Common', []);
// Require the directive source.
// It's important we do this after the module stub
require('./stop_event.directive');
});
// Now we tell angular to load the module
beforeEach(angular.mock.module('Common'));
// now we inject the things required for initializing a directive
beforeEach(angular.mock.inject(function($rootScope, $compile) {
// make a scope
scope = $rootScope.$new();
// use sinon to spy on the parent click function
scope.parentClick = sinon.spy();
// Make a test dom
var dom =
'<div ng-click="parentClick()">' +
' <a stop-event="click"></a> ' +
'</div>'
;
// feed the DOM to angular
element = $compile(dom)(scope);
scope.$digest(); // ¯\_(ツ)_/¯
}));
// Now we can write our test
//---------------------------------------------------------
it('prevents event propogation', function() {
// trigger the client click
element.find('a').click();
// expect the spy to have not been called
expect(scope.parentClick).to.not.have.been.called;
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment