【问题标题】:How can I access my service from module setup in Angular Jasmine Test?如何从 Angular Jasmine Test 中的模块设置访问我的服务?
【发布时间】:2014-11-10 13:47:06
【问题描述】:

我在茉莉花测试中有以下的角...

  beforeEach(module('app'));
  beforeEach(module('app.services'));

  beforeEach(module(function ($provide, Config) {

    reservationCallerJquery = {
      reserveBooking: function (reservationRequestDto, reserveBookingSuccess) {
        doJqueryPost(reservationRequestDto.item,
          "I need a value from my config class",
          reserveBookingSuccess);
      }

    $provide.value("ReservationCaller", reservationCallerJquery);


  }));

但我得到了错误:

错误:[$injector:modulerr] 无法实例化模块函数 ($provide,Config),原因是:错误:[$injector:unpr] 未知提供者:Config

那么如何将我的存根字符串设置为配置中的内容? (配置位于“app.services”中)...我想我需要从那里获取它,但是如何获取呢?

【问题讨论】:

    标签: angularjs jasmine angular-mock


    【解决方案1】:

    您缺少注入,您可以通过以下两种方式之一注入服务、常量、控制器等:

    在注入回调中你可以检索 $injector 然后得到你想要的。

    var myService, location;
    beforeEach(function() {
            inject(function($injector) {
                myService = $injector.get('myService');
                location = $injector.get("$location");
            });
        });
    

    直接获取服务,您可以添加将解析为 ServiceName 但允许您在测试中使用 ServiceName var 的 _ServiceName_:

    var scope, $rootScope, $location;
    beforeEach(inject(function (_$rootScope_, _$location_) {
    
            scope = $rootScope.$new();
            $rootScope = _$rootScope_;
            $location = _$location_
        }));
    

    我的典型测试设置是:

        beforeEach(module('MyApp'));
        beforeEach(module('MyApp.services'));
        beforeEach(module('MyApp.controllers'));
    
        var ctrl, scope, myService;
        beforeEach(inject(function ($rootScope, $controller, $injector) {
            scope = $rootScope.$new();
            ctrl = $controller('MyCtrl', {$scope: scope});
            myService = $injector.get('MyService');
        }));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多