Unit testing AngularJS Controller whilst following best practice
We are building an AngularJS app following some of the best practice guidelines which are outlined here.
Am specifically interested in testing a very simple controller to get up and running with karma.
The controller code is:
angular.module('ttn').controller('Login', Login);
function Login(){
var login = this;
login.title = 'foo bar content here etc';
}
And the spec code is:
describe('Controller: Login', function () {
beforeEach(module('ttn'));
var scope, controller;
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
controller = $controller('Login', {
$scope: scope
});
scope.$digest();
}));
it('should define a title', function () {
expect(scope.title).toBeDefined();
});
});
This fails with expecting undefined to be defined.
If I change the controller to:
angular.module('ttn').controller('Login', Login);
function Login($scope){
$scope.title = 'foo bar whatsit jibber';
}
The test then passes as expected. I am not sure how to reference the controller written in the manner outlined on the above link to get the test to pass.
Since your controller doesn't use $scope, you shouldn't be injecting it and using it in your tests. Instead you should be checking for title on your controller:
describe('Controller: Login', function () {
beforeEach(module('ttn'));
var controller;
beforeEach(inject(function ($controller) {
controller = $controller('Login', {});
}));
it('should define a title', function () {
expect(controller.title).toBeDefined();
});
});
Plunkr
链接地址: http://www.djcxy.com/p/39120.html