Testing angular directives with Jasmine
Testing an Angular directives with Jasmine
HTML
<script src="http://jasmine.github.io/1.3/lib/jasmine.js"></script>
<script src="http://jasmine.github.io/1.3/lib/jasmine-html.js"></script>
<link rel="stylesheet" href="http://jasmine.github.io/1.3/lib/jasmine.css">
<script src="http://code.angularjs.org/1.2.9/angular.js"></script>
<script src="http://code.angularjs.org/1.2.9/angular-mocks.js"></script>
JavaScript
//--- CODE --------------------------
var myApp = angular.module('myApp', []);
myApp.directive('myButton', function() {
return {
restrict: 'E',
template:'<button class="btn btn-primary">MyButtonLabel</button>',
replace: true
};
});
myApp.directive('myDirective', function($compile){
return {
replace: true,
transclude: false,
restrict: 'E',
scope: false,
link: function postLink(scope, iElement, iAttrs) {
iElement.html('<my-button>MyButtonLabel</my-button>');
$compile(iElement.contents())(scope);
}
};
});
// ---SPECS-------------------------
describe('myApp', function () {
var element;
beforeEach(function () {
module('myApp');
element = angular.element('<my-directive></my-directive>');
inject(function ($rootScope, $compile) {
var scope = $rootScope.$new();
$compile(element)(scope);
scope.$digest();
});
});
it('says MyButtonLabel', function () {
expect(element.text()).toBe('MyButtonLabel');
});
});
// --- Runner -------------------------
(function () {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function (spec) {
return htmlReporter.specFilter(spec);
};
var currentWindowOnload = window.onload;
window.onload = function () {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
}
})();