SO: Testing angular directive with Mocha and Sinon
http://angularjs.org/
by miphe
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/mocha/2.0.1/mocha.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/mocha/2.0.1/mocha.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/chai/1.9.2/chai.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/sinon.js/1.7.3/sinon-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.min.js"></script>
<!-- We are going to use Mocha + Chai setup for testing -->
<script>
mocha.setup('bdd');
var expect = chai.expect;
</script>
<body>
<div id="mocha"></div>
</body>
<!-- Adding angular mocks to have 'module' and 'inject' functions -->
<script src="http://code.angularjs.org/1.3.0/angular-mocks.js"></script>
JavaScript
// App
var myApp = angular.module('myApp',[]);
myApp.directive('pers', function() {
return {
restrict: 'E',
template: '<h2 ng-click="clickFunction()" ng-model="person">Person</h2>',
};
});
// Test suite
describe('Pers directive', function() {
var $scope,
compiled,
template = '<pers></pers>';
beforeEach(module('myApp'));
beforeEach(inject(function($compile, $rootScope) {
$scope = $rootScope.$new();
$scope.clickFunction = sinon.spy();
compiled = $compile(template)($scope);
$scope.$digest();
}));
afterEach(function() {
if (typeof $scope.clickFunction.restore == 'function') {
$scope.clickFunction.restore();
}
});
it('should render directive', function() {
el = compiled.find('h2');
expect(el.length).to.equal(1);
});
it('should run clickFunction() when clicked', function() {
el = compiled.find('h2');
el.triggerHandler('click');
expect($scope.clickFunction.calledOnce).to.be.true
});
});
// Run tests
mocha.run();