3

我有一个简单的控制器:

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
4

1 回答 1

5

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

基本上你需要使用这个服务来创建控制器。我创建了一个 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>
于 2015-03-10T12:21:14.030 回答