Angular - 在'it'函数回调中未传递$控制器失败测试,​​为什么?

问题描述:

这里有一位测试新手,我试图为控制器写一些Jasmine/Karma测试。我被给了一个样本测试来处理和构建,在这里,$controller被传递给it块的函数的参数。这导致测试通过正常。

我已经成功地为其他控制器编写了测试这个应用程序,我还没有看到$controller曾经在那里通过。所以我试图按照我所知道的,但是当我删除$controller时,测试失败了,因为它正在寻找依赖项(我应该通过$provide.valuebeforeEach ...中给出?)。

这里的控制器代码 -

(function() { 
    'use strict'; 

    angular 
    .module('myApp') 
    .controller('EntryAddController', EntryAddController); 

    function EntryAddController($scope, $state, moment, $sanitize, dogList, catList, months, frequencies, EntryFactory, $modal, toastr, $log) { 
    var vm = this; 
    var now = moment(); 
    var tomorrow = now.add(1, 'days').toDate(); 
    var to = now.subtract(1, 'days').add(12, 'months').toDate(); 

    vm.fromDay = tomorrow; 
    vm.minDay = tomorrow; 

    start(); 

    function start() { 
     //some logic here 
    } 
})(); 

这里的示例代码中我得到了(注意是it块) -

(function() { 
    'use strict'; 



describe('Entry Add Controller', function(){ 

    describe('EntryAddController', function() { 

     var vm, $rootScope, $controller; 

     beforeEach(module('myApp')); 

     beforeEach(function() { 
     inject(function(_$rootScope_, _$controller_) { 
      $rootScope = _$rootScope_; 
      $controller = _$controller_; 
     }); 
     }); 

     describe('EntryAddController', function() { 
     var $scope; 

     beforeEach(function createChildScopeForTheTest() { 
      $scope = $rootScope.$new(); 
     }); 

     afterEach(function disposeOfCreatedChildScope() { 
      $scope.$destroy(); 
     }); 

     it('expects fromDate and toDate to be defined', function($controller) { 
      vm = $controller('EntryAddController', { $scope: $scope }); 

      expect(vm.fromDay).toBeDefined(); 
     }); 

     }); 
    }); 
    }); 

})(); 

那么,为什么,当我从参数中删除$controllerit块中的函数,它会抛出这个错误?

Error: [$injector:unpr] Unknown provider: dogListProvider <- dogList <- EntryAddController 

是什么it块的这两个版本之间的差异?

it('expects fromDate and toDate to be defined', function($controller) { 
    vm = $controller('EntryAddController', { $scope: $scope }); 

    expect(vm.fromDay).toBeDefined(); 
}); 

it('expects fromDay to be defined', function() { 
    vm = $controller('EntryAddController', { $scope: $scope }); 

    expect(vm.fromDay).toBeDefined(); 
}); 

可以包括一个it()语句中的函数的唯一参数是doneJasmine Asynchronous Support

it("should support async execution of test preparation and expectations", function(done) { 
    value++; 
    expect(value).toBeGreaterThan(0); 
    done(); 
}); 

,你叫它$controller的事实你功能是无关紧要的,它将实际上是done功能,而不是您的控制器。

您应该从该功能中删除参数并解决您的未知提供者错误。

+0

谢谢!我认为是这种情况,但并非100%确定。 – cssun25