Skip to content

Commit 8013fa8

Browse files
committed
Show how to test a method in a unit test
1 parent af0eaa3 commit 8013fa8

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

docs/content/guide/dev_guide.mvc.understanding_controller.ngdoc

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,59 @@ describe('state', function() {
283283
});
284284
</pre>
285285

286+
Functions or methods in a controller can be tested as well. Rather than take arguments or return values
287+
directly, they are more likely to read and write attributes on the scope, as shown below, because that's
288+
compatible with how data binding works.
289+
290+
<pre>
291+
function PasswordCtrl($scope) {
292+
$scope.password = '';
293+
$scope.grade = function() {
294+
var size = $scope.password.length;
295+
if (size > 8) {
296+
$scope.strength = 'strong';
297+
} else if (size > 3) {
298+
$scope.strength = 'medium';
299+
} else {
300+
$scope.strength = 'weak';
301+
}
302+
}
303+
}
304+
</pre>
305+
306+
and the test is straight forward
307+
308+
<pre>
309+
describe('myController function', function() {
310+
311+
describe('myController', function() {
312+
var scope, ctrl;
313+
314+
beforeEach(inject(function($rootScope, $controller) {
315+
scope = $rootScope.$new();
316+
$controller(PasswordCtrl, {$scope: scope});
317+
}));
318+
319+
it('should grade short passwords as weak', function() {
320+
scope.password = 'abc';
321+
scope.grade();
322+
expect(scope.strength).toEqual('weak');
323+
});
324+
325+
it('should grade long passwords as strong', function() {
326+
scope.password = 'abcdefghijklm';
327+
scope.grade();
328+
expect(scope.strength).toEqual('strong');
329+
});
330+
});
331+
});
332+
</pre>
333+
334+
Notice that the test is not only much shorter but it is easier to follow what is going on. We say
335+
that such a test tells a story, rather then asserting random bits which don't seem to be related.
336+
337+
338+
286339

287340
## Related Topics
288341

0 commit comments

Comments
 (0)