Skip to content
This repository was archived by the owner on Sep 3, 2021. It is now read-only.

Commit 41d1c18

Browse files
committed
feat(controller): recipe for testing controllers
1 parent e2df60c commit 41d1c18

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

src/controller.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
(function() {
2+
'use strict';
3+
4+
function SampleController($scope) {
5+
var vm = this;
6+
7+
vm.foo = 'bar';
8+
9+
vm.bar = function() {
10+
vm.foo = 'baz';
11+
};
12+
13+
vm.doSomething = function() {};
14+
15+
$scope.$watch('baz', function(newVal) {
16+
if (newVal) {
17+
vm.baz = newVal + 'bar';
18+
}
19+
});
20+
21+
$scope.$on('$destroy', function() {
22+
vm.doSomething();
23+
});
24+
25+
//scope.$emit()
26+
//scope.$broadcast()
27+
//scope.$on()
28+
//scope.$apply()
29+
}
30+
31+
angular.module('myApp', [])
32+
.controller('SampleController', SampleController);
33+
}());

test/controller.spec.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
describe('SampleController', function() {
2+
var $rootScope,
3+
ctrl, scope;
4+
5+
beforeEach(module('myApp'));
6+
7+
beforeEach(inject(function( _$rootScope_, _$controller_) {
8+
$rootScope = _$rootScope_;
9+
scope = $rootScope.$new();
10+
11+
ctrl = _$controller_('SampleController', {
12+
$scope: scope
13+
});
14+
}));
15+
16+
it('should expose a property', function() {
17+
expect(ctrl.foo).toBe('bar');
18+
});
19+
20+
it('should expose a method', function() {
21+
ctrl.bar();
22+
expect(ctrl.foo).toBe('baz');
23+
});
24+
25+
it('should have a watcher', function() {
26+
scope.baz = 'foo';
27+
scope.$digest();
28+
expect(ctrl.baz).toBe('foobar');
29+
});
30+
31+
it('should do something on $destroy', function() {
32+
spyOn(ctrl, 'doSomething');
33+
scope.$destroy();
34+
expect(ctrl.doSomething).toHaveBeenCalled();
35+
});
36+
});

0 commit comments

Comments
 (0)