Testing angular controllers with Jasmine
Testing angular controllers with Jasmine
by mckennatim
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,
service;
beforeEach(function () {
module('myApp.controllers');
});
// Mocking service?
beforeEach(module(function ($provide) {
service = { Arrive: function (firstname, lastname) {
if (firstname && lastname) {
return true;
}
}};
$provide.value('MyService', service);
}));
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);
});
it('checks that Arrived is correctly used', function() {
// Arrange
spyOn(service, 'Arrive');
// Act
scope.Arrived('Franz', 'Kafka');
// Assert
expect(service.Arrive).toHaveBeenCalledWith('Franz', 'Kafka');
});
});
});
// --- Runner -------------------------
(function () {
var jasmineEnv = jasmine.getEnv();
...