TypeError: undefined 不是构造函数(评估 'angular.controller('myView')')



在对两个测试用例进行业力/茉莉单元测试时,我会遇到以下错误。我尝试通过在规格文件中添加angular.controller修改控制器来尝试,即使是这样。不工作。有任何方法可以解决吗?

 TypeError: undefined is not a constructor (evaluating 'angular.controller('myView')') 

myview.spec.js

// myView.spec.js
(function(){
describe('controller: myView', function(){

     var module,myView,$q, $rootScope, $scope, uiGridConstants, overviewService, commonService, $timeout;
    beforeEach(function() {
        module = angular.module('app.myView');
        controller= angular.controller('myView')
    });
    beforeEach(inject(function ($controller, _$q_, _$rootScope_, _$timeout_) {
        $q= _$q_;
        $rootScope = _$rootScope_;
         $timeout= _$timeout_;
        myView= $controller('myView', {
            $q : _$q_,
            $rootScope :  _$rootScope_,
             $timeout:  _$timeout_
        });

    }));
    describe("myViewto be defined", function() {
        it("should be created successfully", function () {
            expect(controller).toBeDefined();
        });
        it("overview should be defined", function () {
            expect(myView()).toBeDefined();
        });
    });
});
})();

和myview.js

(function() {
    'use strict';
    angular
        .module('app.myView')
        .controller('myView', myView);
    function myView($q, $rootScope, $scope, uiGridConstants, myViewService, commonService, $timeout) {
        var vm = this;
        vm.callFeedback = function () { };
})();

共享代码

// myView.spec.js
(function(){
describe('myView', function(){
  var $controller, myView;
   //we use angular-mocks to specify which modules we'll need within this  
   //test file. 
   beforeEach(angular.mock.module('app.myView'));
   // Inject the $controller service to create instances of the controller 
   //(myView) we want to test
   beforeEach(inject(function(_$controller_) {
      $controller = _$controller_;
      myView = $controller('myView', {});
    }));
   // Verify our controller exists
   it('should be defined', function() {
      expect(myView).toBeDefined();
   });
  });
})();

我们将_$controller_设置为我们创建的$controller变量,然后通过调用$ Controller('MyView',{}(来创建控制器的实例。第一个参数是我们要测试的控制器的名称,第二个参数是我们控制器的依赖项的对象。

您应该将注入的参数传递给控制器,如下所示:

(function() {
'use strict';
angular
    .module('app.myView')
    .controller($q,$rootScope,$scope,uiGridConstants,'myView', myView);
function myView($q, $rootScope, $scope, uiGridConstants, myViewService, commonService, $timeout) {
    var vm = this;
    vm.callFeedback = function () { };

}(((;

还确保您的模块具有angular.module('app.myView',['uiGridConstants', ...'etc']);

中的所有必要依赖性

最新更新