Reputation: 1140
I'm having trouble understanding how the scope gets initialized in karma tests. i'm expecting a scope variable to be preset when the test runs, but it keeps coming back as undefined.
What am I missing?
Test Case
describe('loginController', function() {
beforeEach(module('app'));
var $controller, $scope;
beforeEach(inject(function(_$controller_, $rootScope){
$controller = _$controller_;
$scope = $rootScope.$new();
}));
describe('$scope.login', function() {
beforeEach(function() {
controller = $controller('loginController', { $scope: $scope });
});
it('checks it initialized', function() {
expect($scope.foo).toEqual('foo');
expect($scope.bar).toEqual('bar');
//expect($scope).toBeDefined();
//expect($scope.loginData.userName).toEqual('');
//expect($scope.loginData.password).toEqual('');
});
The controller:
angular.module('app').controller('loginController', ['$location',
'authService', function($scope, $location, authService) {
$scope.foo = 'foo';
$scope.bar = 'bar';
$scope.loginData = {
userName: '',
password: ''
};
}]);
Upvotes: 2
Views: 4407
Reputation: 1140
I refactored the test code and now it works:
describe('loginController', function() {
beforeEach(module('app'));
var controller, scope;
beforeEach(inject(function($controller, $rootScope){
scope = $rootScope.$new();
console.log('scope1', scope);
controller = $controller('loginController', {
$scope: scope
});
}));
describe('login', function() {
it('sets variables ', function() {
expect(scope).toBeDefined();
expect(scope.loginData).toBeDefined();
expect(scope.loginData.userName).toEqual('');
expect(scope.loginData.password).toEqual('');
});
});
});
Upvotes: 5
Reputation: 491
try injecting $controller to the function where you instantiate the controller:
beforeEach(inject(function($controller) {
controller = $controller('loginController', { $scope: $scope });
}));
Upvotes: 0