【问题标题】:Unknown Provider when testing a modal dialog测试模态对话框时的未知提供者
【发布时间】:2015-07-09 01:15:07
【问题描述】:

前言:我对 Angular 很陌生,对单元测试也很陌生。温柔点。

我正在尝试在控制器上为引导模式窗口运行单元测试。

在启动模式时,我正在通过一个名为 thisVersion 的对象,如下所示:

 function showShareDialog(thisVersion){
        var modalInstance = $modal.open({
            templateUrl: 'app/shares/views/shares-dialogue.tpl.html',
            controller: 'SharesCtrl',
            resolve:{
                thisVersion:function(){
                    return thisVersion;
                }
            }
        });
        modalInstance.result.then(function (validated) {
            // .. more code
        });
    }    

一旦Shares Controller 被实例化,我就会在thisVersion 上调用一个方法

thisVersion.getList('shares').then(function(result){
    $scope.shares = result;
});

thisVersion 作为依赖项被传递给控制器​​,并且一切都按预期工作。

然而,问题是我似乎无法将它注入我的测试套件。我不断收到此错误

错误:[$injector:unpr] 未知提供者:thisVersionProvider

这是(大部分)我的测试套件:

var scope, controller, thisVersion;

  beforeEach(module('app'));
  beforeEach(inject(function ($controller, $rootScope, _thisVersion_) {

        scope = $rootScope.$new();       
        controller = $controller('SharesCtrl', {
            $scope: scope
        });
        thisVersion = _thisVersion_;

    }));

 it('should get a list of all shares',  function(){
     expect(thisVersion.getList).not.toBe('undefined');
 });

我知道我将不得不模拟从 thisVersion.getList() 对 Api 的调用,但现在我只关心让测试套件识别 thisVersion

【问题讨论】:

  • 这个版本是 Angular 服务吗?你只是提到它是一个对象。

标签: angularjs unit-testing jasmine karma-runner karma-jasmine


【解决方案1】:

您需要将thisVersion 注入 $controller,看看它是如何在 $modal.open 中解析的值。

    var modalInstance = $modal.open({
        templateUrl: 'app/shares/views/shares-dialogue.tpl.html',
        controller: 'SharesCtrl',
        resolve:{
            // Resolved properties will be available for DI, into the controller.
            thisVersion:function(){ 
                return thisVersion;
            }
        }
    });

beforeEach(module('app'));
beforeEach(inject(function ($controller, $rootScope, _thisVersion_) {

  scope = $rootScope.$new();

  controller = $controller('SharesCtrl', {
    $scope: scope,
    thisVersion: _thisVersion_ /** inject the service _into_ the controller **/
  });
}));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 2017-02-02
    • 2015-03-04
    • 1970-01-01
    相关资源
    最近更新 更多