DI ➡ mock implementations ➡ isolation
Dependency Injection != Service Locator Pattern
angular.module('MyModule').controller('MyCtrl', function($scope) {
$scope.value = 0;
$scope.maxValue = 2;
$scope.incrementValue = function() {
if ($scope.value < $scope.maxValue) {
$scope.value++;
} else {
$scope.value = 0;
}
};
});
describe('MyCtrl', function() {
var scope, controller;
beforeEach(inject(function($controller, $rootScope) {
scope = $rootScope.$new();
controller = $controller('MyCtrl', {$scope: scope});
}));
it('has correct initial value', function() {
expect(scope.value).toEqual(0); expect(scope.maxValue).toEqual(2);
});
it('increments correctly', function() {
scope.incrementValue(); expect(scope.value).toEqual(1);
scope.incrementValue(); expect(scope.value).toEqual(2);
scope.incrementValue(); expect(scope.value).toEqual(0);
});
});
angular.module('MyModule').controller('MyCtrl', function($scope, $http) {
$scope.incrementValue = function() {
$scope.value = $scope.value < $scope.maxValue ? $scope.value + 1 : 0;
};
$http.get('api/incrementor/config').success(function(data) {
$scope.value = data.initialValue;
$scope.maxValue = data.maxValue;
});
});
// Verify that a request is made and handled (properly)
expect().respond(...);
// Verify that a response is handled (properly) if called
when(...).respond(...);
// Force synchronous execution of pending request(s)
flush();
// Make sure all expect() calls were made
afterEach($httpBackend.verifyNoOutstandingExpectation);
// Make sure there are no calls waiting to be flushed
afterEach($httpBackend.verifyNoOutstandingRequest);
// Use in complex, multi-step specs
$httpBackend.resetExpectations();
describe('MyCtrl', function() {
var scope, createController, httpBackend;
beforeEach(inject(function($controller, $rootScope, $httpBackend) {
scope = $rootScope.$new();
httpBackend = $httpBackend;
createController = function() {
return $controller('MyCtrl', {$scope: scope, $http: $httpBackend});
};
}));
it('sets correct initial values', function() {
// Continued on next slide
});
});
it('sets correct initial values', function() {
httpBackend.expectGET('api/incrementor/config').respond(200, {
initialValue: 0,
maxValue: 2
});
createController();
httpBackend.flush();
expect(scope.value).toEqual(0);
expect(scope.maxValue).toEqual(2);
});
describe('Capitalize Filter', function() {
var filter;
beforeEach(inject(function($filter) {
filter = $filter('capitalize');
}));
it('capitalizes various strings', function() {
var result;
result = filter('unit tests');
expect(result).toEqual('Unit Tests');
result = filter('UNIT TESTS');
expect(result).toEqual('Unit Tests');
});
});
it('tests myDirective', function() {
var element = $compile('<my-directive></my-directive>')($rootScope);
// Fire watches so template expressions are executed
$rootScope.$digest();
// Test element to verify DOM structure/contents
// Test functions and values on $rootScope like with a controller
});