Testing angular controllers with Jasmine
Testing angular controllers with Jasmine
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>
JavaScript
//--- CODE --------------------------
// Create module with controller
angular.module('myApp.controllers', [])
.controller('MyCtrl', ['$scope', 'MyService', function ($scope, MyService) {
$scope.User = {};
$scope.HasUserArrived = false;
$scope.Arrived = function(firstname, lastname) {
$scope.HasUserArrived = MyService.Arrive(firstname, lastname);
return $scope.HasUserArrived;
}
}]);
// ---SPECS-------------------------
describe('myApp', function () {
var scope,
controller;
beforeEach(function () {
module('myApp.controllers');
});
// Mocking service?
beforeEach(module(function ($provide) {
$provide.factory('MyService', function () {
Arrive = function (firstname, lastname) {
if (firstname && lastname) {
return true;
}
}
});
}));
describe('MyCtrl', function () {
beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
controller = $controller('MyCtrl', {
'$scope': scope
});
}));
it('user still not there', function () {
expect(scope.HasUserArrived).toBe(false);
});
// How to test Method "Arrived" of the controller? This here is not working...
// it('user arrives', function () {
// expect(scope.Arrived('Franz', 'Kafka')).toBe(true);
// });
});
});
// --- 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) {
...