Jasmine - 测试控制器是否存在出错

Jasmine - Testing if Controller Exists Getting Error

我有一个简单的控制器:

app.controller("RegisterController", function ($scope, $location) {

    // Do something

});

我想做的就是测试这个控制器是否定义:

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();
    });
});

我收到以下错误:

TypeError: undefined is not a function

你正在尝试测试错误的东西,你不想测试 $controller 这只是 ngMock 中的一个服务,它用于测试你自己的控制器。 https://docs.angularjs.org/api/ngMock/service/$控制器

基本上您需要使用此服务创建控制器。我创建了一个 plunkr 示例。 http://plnkr.co/edit/DQZGZERfCptAlgeBUUqb?p=preview

现在,如果您将控制器的名称更改为 RegisterController1,测试将失败,希望这对您有所帮助。 `

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="jasmine@2.2.1" data-semver="2.2.1" rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/jasmine/2.2.1/jasmine.css" />
    <script data-require="jasmine@2.2.1" data-semver="2.2.1" src="http://cdnjs.cloudflare.com/ajax/libs/jasmine/2.2.1/jasmine.js"></script>
    <script data-require="jasmine@2.2.1" data-semver="2.2.1" src="http://cdnjs.cloudflare.com/ajax/libs/jasmine/2.2.1/jasmine-html.js"></script>
    <script data-require="jasmine@2.2.1" data-semver="2.2.1" src="http://cdnjs.cloudflare.com/ajax/libs/jasmine/2.2.1/boot.js"></script>
    <script data-require="angular.js@1.3.14" data-semver="1.3.14" src="https://code.angularjs.org/1.3.14/angular.js"></script>
    <script data-require="angular-mocks@1.3.14" 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>