25. ES5, Karma, Jasmine, PhantomJS
describe('TodoService', function() {
var TodoService, InitialTodosMock;
// Instantiate Angular JS context
beforeEach(module("app"));
// Register mocks in Angular JS context
beforeEach(module(function($provide) {
InitialTodosMock = [
{
label: 'Test todo',
done: false
}
];
$provide.value('initialTodos', InitialTodosMock);
}));
// Get instance of TodoService with mocked dependencies from Angular JS context
beforeEach(inject(function (_TodoService_) {
TodoService = _TodoService_;
}));
// Oh, ... do the actual testing !!!
it('should have initial todo', function() {
expect(TodoService.todos.length).toBe(1);
expect(TodoService.todos[0].label]).toBe('Test todo');
expect(TodoService.todos[0].done]).toBe(false);
});
});
26. ES5, Karma, Jasmine, PhantomJS
describe('TodoController', function() {
var scope, $rootScope, $controller;
// Instantiate Angular JS context
beforeEach(module('app'));
// Register mocks in Angular JS context
// (sometimes not necessary, we can use real services too, but the Angular context grows...)
beforeEach(module(function($provide) {
var TodoServiceMock = {
todos: [],
addTodo: function() { /*……*/ },
toggleTodo: function() { /*……*/ },
removeDoneTodost() { /*……*/ }
};
$provide.value('TodoService', TodoServiceMock);
}));
// Get instance of TodoController, you know, create new $scope from $rootScope by yourself and stuff...
// It is possible to not use $scope when using 'controllerAs' syntax,
// but you still have to use at least $controller to get the refference to controller itself
beforeEach(inject(function(_$rootScope_, _$controller_, _TodoService_){
$controller = _$controller_;
$rootScope = _$rootScope_;
scope = $rootScope.$new();
$controller('TodoController', {
$scope: scope
TodoService: _TodoService_
});
}));
// Oh, ... do the actual testing !!!
it('should have initial todos', function() {
expect(scope.todos.length).toBe(1);
});
});
27. Issues
• Angular context module(‘app’) must be instantiated to be able to do any
testing. Without Angular context you can’t get access (reference) to your
controllers / services.
• Angular and all other used libraries must be included during testing so that it
is even possible to instantiate Angular context.
• Angular context can grow quite large so that it’s creation will consume
considerable amount of time for every test file.
• Karma exclusion syntax doesn’t follow standard node glob pattern which
can make you go crazy when you try to solve timeout errors caused by
insufficient memory on PhantomJS by splitting test execution into
multiple batches, while supporting dev mode single test execution
(karma uses extra exclude property instead of supporting standard “!”)