I've gone through a few tutorials and basic examples but I'm having a hard time writing unit tests for my controller. I've seen code snippets instantiating controllers and letting angular inject the $rootScope
object which in turn is used to create a new scope
object for the controller. But I can't figure out why ctrl.$scope
? is undefined:
describe('EmployeeCtrl', function () {
var scope, ctrl, $httpBackend;
beforeEach(inject(function (_$httpBackend_, $rootScope, $controller, $filter) {
$httpBackend = _$httpBackend_;
scope = $rootScope.$new();
ctrl = $controller('EmployeeCtrl', { $scope: scope});
expect(ctrl).not.toBeUndefined();
expect(scope).not.toBeUndefined(); //<-- PASS!
expect(ctrl.$scope).not.toBeUndefined(); //<-- FAIL!
}));
});
I ended up using the scope
variable instead of ctrl.$scope
but then on my first test I couldn't figure out how to unit test a function variable inside my controller:
Controller:
function EmployeeCtrl($scope, $http, $filter, Employee) {
var searchMatch = function (haystack, needle) {
return false;
}
}
Broken unit test:
it('should search ', function () {
expect(ctrl.searchMatch('numbers','one')).toBe(false);
});
This is what I get
TypeError: Object # has no method 'searchMatch'
How do you test that function? As a workaround I moved my method to $scope so I could test for scope.searchMatch
but I was wondering if this is the only way.
Finally, on my tests is appears $filter
is undefined too, how do you inject it? I tried this but didn't work:
ctrl = $controller('EmployeeCtrl', { $scope: scope, $filter: $filter });
Thanks
Update:
The method mentioned above to inject $filter works just fine.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…