1

我在对两个测试用例进行业力/茉莉花单元测试时遇到以下错误。我尝试通过在规范文件中添加 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 () { };
})();
4

2 回答 2

3

分享以下代码

// 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', {}) 创建控制器的实例。第一个参数是我们要测试的控制器的名称,第二个参数是我们控制器的依赖对象。

于 2018-05-10T09:12:00.893 回答
0

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

(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']);

于 2018-05-16T22:47:34.133 回答