i have a simple controller:
app.controller("RegisterController", function ($scope, $location) {
// Do something
});
And all i am trying to do is to test this controller is defined:
describe('RegisterController', function() {
var $rootScope, $scope, $controller;
beforeEach(module('myApp'));
beforeEach(inject(function(_$rootScope_, _$controller_){
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
$controller = _$controller_;
$controller('RegisterController', {'$rootScope' : $rootScope, '$scope': $scope});
}));
it('should exist', function() {
expect($controller).toBeDefined();
});
});
And i get the following error:
TypeError: undefined is not a function
You are trying to test the wrong thing, you don't want to test $controller which is just a service in ngMock, which is used to test your own controller. https://docs.angularjs.org/api/ngMock/service/$controller
basically you need to create the controller using this service. I have created a plunkr example. http://plnkr.co/edit/DQZGZERfCptAlgeBUUqb?p=preview
now if you change the name of the controller to RegisterController1 the test will fail, hope this helps. `
var app = angular.module('myApp',[]);
app.controller("RegisterController", function ($rootScope, $scope) {
// Do something
});
describe('RegisterController', function() {
var $rootScope, $scope, $controller,registerController;
beforeEach(module('myApp'));
beforeEach(inject(function(_$rootScope_, _$controller_){
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
$controller = _$controller_;
registerController = $controller('RegisterController', {'$rootScope' : $rootScope, '$scope': $scope});
}));
it('should exist', function() {
expect(registerController).toBeDefined();
});
});
`
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<link data-require="[email protected]" data-semver="2.2.1" rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/jasmine/2.2.1/jasmine.css" />
<script data-require="[email protected]" data-semver="2.2.1" src="http://cdnjs.cloudflare.com/ajax/libs/jasmine/2.2.1/jasmine.js"></script>
<script data-require="[email protected]" data-semver="2.2.1" src="http://cdnjs.cloudflare.com/ajax/libs/jasmine/2.2.1/jasmine-html.js"></script>
<script data-require="[email protected]" data-semver="2.2.1" src="http://cdnjs.cloudflare.com/ajax/libs/jasmine/2.2.1/boot.js"></script>
<script data-require="[email protected]" data-semver="1.3.14" src="https://code.angularjs.org/1.3.14/angular.js"></script>
<script data-require="[email protected]" data-semver="1.3.14" src="https://code.angularjs.org/1.3.14/angular-mocks.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<h1>Hello Plunker!</h1>
</body>
</html>