Testing Angular directives with Jasmine
Drop in your code, drop in your Jasmine specs, and away you go!
by munir
HTML
<script src="http://pivotal.github.io/jasmine/lib/jasmine-1.3.1/jasmine.js"></script>
<script src="http://pivotal.github.io/jasmine/lib/jasmine-1.3.1/jasmine-html.js"></script>
<link rel="stylesheet" href="http://pivotal.github.io/jasmine/lib/jasmine-1.3.1/jasmine.css">
<script src="http://code.angularjs.org/1.0.5/angular.js"></script>
<script src="http://code.angularjs.org/1.0.5/angular-mocks.js"></script>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Jasmine Spec Runner</title>
<script type="text/javascript">
(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();
}
})();
</script>
</head>
<body></body>
</html>
JavaScript
//--- CODE --------------------------
var myApp = angular.module('myApp', []);
myApp.directive('myDrtv', function () {
return {
restrict: 'E',
// Better to externalize to templateUrl, this is for demonstration sake
template: '<div>Hello {{name}}</div>',
replace: false
};
});
// ---SPECS-------------------------
describe('myApp', function () {
var element;
var name = 'Homer';
var controller;
var expectedUrl = '/someUrl?key1=value1';
var $httpBackend;
beforeEach(function () {
module('myApp');
element = angular.element('<my-drtv/>');
inject(function ($rootScope, $compile) {
var scope = $rootScope.$new();
scope.name = name;
$compile(element)(scope);
scope.$digest();
});
});
it('says hello', function () {
console.log(element);
expect(element.text()).toBe('Hello Homer');
});
it('test is over',function(){
console.log('<div class='123456789'><div>');
expect('1').toBE('1');
});