Testing angular controllers with Jasmine
Testing angular controllers 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 --------------------------
(function (angular) {
// Create module
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', '$filter', '$http', function ($scope, $filter, $http){
$scope.date = $filter('date')('1234', 'dd-MMM-yyyy');
$http.get("something");
}]);
})(angular);
// ---SPECS-------------------------
describe('myApp', function () {
var scope,
controller;
var http;
beforeEach(function () {
module('myApp');
});
describe('MyCtrl', function () {
beforeEach(inject(function ($rootScope, $controller, $filter, $http) {
http = $http;
window.filter = $filter;
spyOn(http, 'get');
spyOn(window, 'filter').andCallThrough();
scope = $rootScope.$new();
controller = $controller('MyCtrl', {
'$scope': scope,
'$http': http,
'$filter' : filter
});
}));
it('call $filter("date") and test()', function () {
expect(scope.date).toBe('01-Jan-1970');
expect(http.get).toHaveBeenCalled();
expect(window.filter).toHaveBeenCalledWith('date');
});
});
});
// --- 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();
}
})();