如何在茉莉花测试中模拟servicecall?

时间:2016-02-27 23:34:34

标签: angularjs angularjs-directive karma-jasmine spy

我创建了一个角度自定义指令,其中包含一个名为scriptingService的服务。目标是使用spyOn模拟服务调出。这是测试的一部分:

 beforeEach(inject(function ($rootScope, $compile,_scriptingService_) {
      scope = $rootScope.$new();
      scope.row = 1;

      scriptingService = _scriptingService_;
      Restangular = _Restangular_;

      spyOn(Restangular, 'all').and.callThrough();

      spyOn(scriptingService, 'getScript').and.callThrough();

      element = angular.element('<ul id="rows" ui-list="row">');
      $compile(element)(scope);
      scope.$digest();
    }));

这是指令代码:

.directive('uiList', [
    function(scriptingService) {
        return {
            scope: {
                lengthModel: '=uiList'
            },
            link: function(scope, elm, attrs) {
                scope.$watch('lengthModel', function(newVal) {
                    scope.test=2;
                    console.log('kut');

                    scriptingService.getScript(request).then(function(scripts){
                        scope.scripts = scripts;
                    });

                });
            }
        };
    }
]);

但是我收到了错误:

RestangularProvider <- Restangular <- scriptingService

如何模拟sc​​riptingService并确保调用该方法? Plunker ref:http://plnkr.co/edit/CDc7EV?p=preview

1 个答案:

答案 0 :(得分:0)

这里有几个问题:

  1. 与上述评论一样,您需要为callThrough功能使用较新版本的jasmine,而Restangular需要使用下划线,因此需要在html中引用文件

  2. 此外,需要为您的指令修复依赖注入,因为它无法正确注入scriptingService,因为scriptingService.getScript从未允许它调用scriptingServiceundefined。问题在于

    [ function(scriptingService) {}]
    

    无法将scriptingService注入uiList。它最终只是undefined

    它必须是

    ['scriptingService', function(scriptingService) {}]
    

    OR

    function(scriptingService) {}
    

    供参考:https://docs.angularjs.org/guide/di#dependency-annotation

  3. request在此代码中被使用时从未被定义,我不确定它应该是什么。

    scriptingService.getScript(request).then(function(scripts) {
     scope.scripts = scripts;
    });
    
  4. 修复这些问题后,测试仍然失败,说错误:意外请求:GET /脚本。

    我能够通过将$httpBackend(这是一种用于模拟角度的http调用的服务)注入测试并期望请求来解决这个问题。所以我改变了

    inject(function ($rootScope, $compile,_scriptingService_,_Restangular_)
    

    inject(function ($rootScope, $compile,_scriptingService_,_Restangular_, $httpBackend)
    

    并添加了此

    $httpBackend.expectGET("/scripting").respond([]);
    

    spyOn之后,测试通过了。我不确定这个http调用应该返回什么,但这只是一个如何测试它的例子。

    供参考: https://docs.angularjs.org/api/ngMock/service/ $ httpBackend