5

我正在尝试对使用某些资源的服务的指令进行单元测试。我遇到的问题是,当我模拟get资源的方法时,它将被模拟,但不会调用回调函数。因此,结果不会是预期的。

我尝试按照这里spyOn的建议使用来模拟资源,而且,但都没有奏效。当我调试代码时,它会到达 get 方法,但永远不会调用 get 回调函数,因此,设置我的值的内部回调永远不会被调用。我不确定我的方法是否正确,感谢您的建议。$httpBackend.whenmyCallback

/ 资源

.factory ('AirportTimeZone', function($resource){
  return $resource('/api/airport/:airportId/timezone',{airportId: '@airportId'});
})

/ 使用我的资源的服务:

angular.module('localizationService', [])
.factory('LocalizationService', ['AirportTimeZone','CurrentLocalization',
     function (AirportTimeZone,CurrentLocalization) {

    function getAirportTimeZone(airport,myCallback){
      var options = {}
      var localOptions = AirportTimeZone.get({airportId:airport}, function(data){
          options.timeZone = data.timeZoneCode
          myCallback(options)
      });
    }
})

/ 指令

.directive('date',function (LocalizationService) {
    return function(scope, element, attrs) {
        var airTimeZone
         function updateAirportTimeZone(_airportTimeZone){
            airTimeZone = _airportTimeZone.timeZone
            // call other stuff to do here
        }
        ....
        LocalizationService.getAirportTimeZone(airport,updateAirportTimeZone)
        ....
        element.text("something");
    }
});

/ 测试

describe('Testing date directive', function() {
    var $scope, $compile;
    var $httpBackend,airportTimeZone,currentLocalization

    beforeEach(function (){
        module('directives');
        module('localizationService');
        module('resourcesService');
    });

    beforeEach(inject(function (_$rootScope_, _$compile_,AirportTimeZone,CurrentLocalization) {
        $scope = _$rootScope_;
        $compile = _$compile_;
        airportTimeZone=AirportTimeZone;
        currentLocalization = CurrentLocalization;

 //        spyOn(airportTimeZone, 'get').andCallThrough();
 //        spyOn(currentLocalization, 'get').andCallThrough();

    }));

    beforeEach(inject(function($injector) {
        $httpBackend = $injector.get('$httpBackend');
//        $httpBackend.when('GET', '/api/timezone').respond({timeZone:'America/New_York',locale:'us-en'});
//        $httpBackend.when('GET', '/api/airport/CMH/timezone').respond({timeZone:'America/New_York'});
    }))

    describe('Date directive', function () {
        var compileButton = function (markup, scope) {
            var el = $compile(markup)(scope);
            scope.$digest();
            return el;
        };

        it('should',function() {
            var html = "<span date tz='airport' format='short' airport='CMH' >'2013-09-29T10:40Z'</span>"
            var element = compileButton(html,$scope)
            $scope.$digest();

            expected = "...."
            expect(element.html()).toBe(expected);


        });
    });
})
4

1 回答 1

4

如上所述:

使用 设置响应后$httpBackend.when,您仍然需要调用$httpBackend.flush()以清除模拟响应。

参考:http : //docs.angularjs.org/api/ngMock .$httpBackend -刷新 http 请求部分

于 2013-10-10T13:15:46.750 回答