Some notes - I had to work with AngularJs tests today and needed to look into Jasmine and mocking enough and import enough to have running tests. I use the Chutzpah test runner to run the
Jasmine Tests.
The unit test below should get you started writing tests for controllers in AngularJs. The key concepts is to import jQuery, Bootstrap, Angular Animate, Angular-Mocks and your
module and controller through using the reference path syntax at the top and then define a beforeEach that capture the _$controller_ and $_rootScope_ variables and using
$rootScope.$new() to create a scope. But in my case I also had to specify a provided factory 'bootstrappedData' since my controller reads the 'model' property inside that.
By specifying the value this provided factory returns at the top of each tests, I got the amount of DRY I needed to get started testing. I had to this since my controller
got the data in an indirect manner, using he factory. I then create a new instance of the controller after updating the 'bootstrappedData' factory.
///
///
///
///
///
///
///
describe('someController works', function () {
beforeEach(module('app'));
var $scope;
var $rootScope;
var $controller;
var $bootstrappedData;
var $repository;
var ctrl;
var provide;
beforeEach(module(function ($provide) {
provide = $provide;
}));
beforeEach(module(function ($provide) {
$provide.factory('repository', function () {
return {
model: {
}
};
});
}));
beforeEach(inject(function (_$controller_, _$rootScope_) {
$controller = _$controller_;
$rootScope = _$rootScope_;
scope = $rootScope.$new();
}));
it('Creates the AngularJs controller someController', function () {
provide.factory('bootstrappedData', function () {
return {
model: {
}
};
});
ctrl = $controller('someController', { $scope: scope });
expect(ctrl).not.toBe(null);
});
it('Method someproperty returns expected', function () {
provide.factory('bootstrappedData', function () {
return {
model: {
SomeProperty: '3'
}
};
});
ctrl = $controller('KontrollskjemaController', { $scope: scope });
var someprop = scope.isSomeConditionalPropertyReturningTrueIfSomePropertyIsThree;
expect(someprop).toBe(true);
});
});
A tip is to add a file called Chutzpah.json and ignoring well known Javascript libraries to only run code coverage on your own code:
{
"CodeCoverageExcludes": [ "*\\jquery.js", "*\\angular.js", "*\\bootstrap.min.js", "*\\jquery*", "*\\angular-animate.min.js" ]
//"CodeCoverageIncludes": [ "*\\*Spec.js" ]
}