Skip to content

Instantly share code, notes, and snippets.

@roine
Last active May 18, 2016 10:49
Show Gist options
  • Save roine/9621298 to your computer and use it in GitHub Desktop.
Save roine/9621298 to your computer and use it in GitHub Desktop.
Some notes on testing AngularJs with Jasmine and Karma.
describe('controllerCtrl', function () {
var $controller,
$rootScope,
$scope;
beforeEach(module('controller'));
beforeEach(inject(function ($injector) {
$controller = $injector.get('$controller');
$rootScope = $injector.get('$rootScope');
$scope = $rootScope.$new();
ctrlLoader = function () {
return $controller('controllerCtrl', {
$scope: $scope
});
};
}));
it('should do something awesome', function () {
ctrlLoader();
// a method in controllerCtrl change $scope.awesome to true
$scope.somethingAwesome();
expect($scope.awesome).toBeTruthy();
});
});
describe('directive', function () {
beforeEach(module('directive'));
beforeEach(inject(function ($injector) {
var el = angular.element('<div my-directive>hello</div>');
// get $compile and $rootScope
$compile = $injector.get('$compile');
$rootScope = $injector.get('$rootScope');
// create a new scope
$scope = $rootScope.$new();
// compile the created element with the create scope
$compile(el)($scope);
// Run all the watches on the current scope
$scope.$digest();
}));
it('should add something awesome to my element', function () {
expect(el.contains('something awesome')).toBeTruthy();
});
});
describe('spyOn', function () {
/**
* see controllerSpec.js
*/
it('should have trigger an alert with an error message', function () {
spyOn(window, 'alert');
$scope.loadData();
expect(window.alert).toHaveBeenCalledWith('error');
spyOn(window, 'alert').and.returnValue('failed loading data');
$scope.loadData();
expect(window.alert).toHaveBeenCalledWith('failed loading data');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment