Reputation: 117
I am unit testing with karma/jasmine and am having errors with unit testing my controller. Controller code:
angular.module('app.controllers', [])
.controller('myctrl1',[function($scope){
$scope.test = "this worked";
}])
Unit Test Code:
describe('Controllers', function(){ //describe your object type
beforeEach(module('app.controllers')); //load module<br />
describe('Running Test for :',function(){ //describe your app name<br />
var myctrl;
beforeEach(inject(function($controller){ //instantiate controller using $controller service
myctrl = $controller('myctrl1');
}));
it('Test scope var', function(){ //write tests
expect($scope.test).toBe('this worked'); //pass
});
});
});
I am getting the following error:
TypeError: Cannot set property 'test' of undefined
ReferenceError: $scope is not defined
Upvotes: 1
Views: 2452
Reputation: 24874
Modify your test to:
angular.module('app.controllers', ['ngMockE2E'])
.controller('myCtrl1', function($scope) {
$scope.test = "this worked";
});
describe('Main Controller test suite', function() {
describe('myCtrl1', function() {
var $scope;
beforeEach(module('app.controllers'));
beforeEach(inject(function($rootScope, $controller) {
$scope = $rootScope.$new();
$controller('myCtrl1', {
$scope: $scope
});
}));
it('Test scope var', function() {
expect($scope.test).toBe('this worked'); //pass
});
});
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine-html.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/boot.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular-mocks.js"></script>
</head>
<body>
<h1>Angular controller test with Jasmine</h1>
</body>
</html>
Reference: https://docs.angularjs.org/guide/unit-testing#testing-a-controller
Upvotes: 3