SO: Testing angular directive with Mocha and Sinon
http://angularjs.org/
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="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/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.1.5/angular-mocks.js"></script>
JavaScript
// App
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
$scope.person = 'Mr';
$scope.clickFunction = function() {
// Some important functionality
};
});
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,
$controller,
compiled,
template = '<pers></pers>';
beforeEach(module('myApp'));
beforeEach(inject(function($compile, $rootScope, $controller) {
$scope = $rootScope.$new();
$controller('MyCtrl', {$scope: $scope});
compiled = $compile(template)($scope);
/*
At this point, $scope is missing functionality - how come?
$scope.$digest => can not be called
$scope.$apply => can not be called
*/
//$scope.$digest();
//$scope.$apply();
}));
afterEach(function() {
compiled = null;
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');
sinon.spy($scope, 'clickFunction');
// Here's the problem! How can I trigger a click?
el.triggerHandler('click');
expect($scope.clickFunction.calledOnce).to.be(true)
});
});
// Run tests
mocha.run();