I need to apply testing to a particular controller.
Testing this controller is ok:
angular.module('app', []).controller('PasswordController', function PasswordController($scope) {
$scope.password = '';
$scope.grade = function () {
var size = $scope.password.length;
if (size > 8) {
$scope.strength = 'strong';
} else if (size > 3) {
$scope.strength = 'medium';
} else {
$scope.strength = 'weak';
}
};
});
But I'd like to test:
angular.module('app', []).controller('PasswordController', function PasswordController($scope) {
var vm = this;
vm.password = '';
function grade() {
var size = vm.password.length;
if (size > 8) {
vm.strength = 'strong';
} else if (size > 3) {
vm.strength = 'medium';
} else {
vm.strength = 'weak';
}
};
});
I tried to test the controller using the code below:
describe('Test', function () {
beforeEach(module('app'));
var MainCtrl, scope;
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
MainCtrl = $controller('PasswordController', {
$scope: scope
});
}));
it('Should not throw Exception', function () {
scope.password = 'abc';
var call = function () {
MainCtrl.grade();
}
expect(call).not.toThrow();
});
});
But I get this error : Expected function not to throw, but it threw TypeError: 'undefined' is n ot a function (evaluating 'MainCtrl.grade()').
This stackOverflow Question help me to apply testing to function inside 'this'. But I want to test functions out of $scope and 'this'...
Any Idea how to apply unit testing to this controller?
AngularJS is written with testability in mind, but it still requires that you do the right thing. We tried to make the right thing easy, but if you ignore these guidelines you may end up with an untestable application.
AngularJS ScopeThe scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an object with the available properties and methods. The scope is available for both the view and the controller.
The grade method is not being attached to the controller;
vm.grade = grade;
Working Plunkr
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With