AngularJS,Unit测试使用依赖于某些资源的服务的指令
发布时间:2020-12-17 10:26:15 所属栏目:安全 来源:网络整理
导读:我正在尝试对使用使用某些资源的服务的指令进行单元测试.我遇到的问题是,当我模拟我的资源的get方法时,它将被模拟,但不会调用回调函数.因此,结果将不是预期的结果. 我试图通过使用spyOn来建模资源,如建议的here,以及$httpBackend.when,但都没有用.当我调试代
我正在尝试对使用使用某些资源的服务的指令进行单元测试.我遇到的问题是,当我模拟我的资源的get方法时,它将被模拟,但不会调用回调函数.因此,结果将不是预期的结果.
我试图通过使用spyOn来建模资源,如建议的here,以及$httpBackend.when,但都没有用.当我调试代码时,它将转到get方法但get调用函数永远不会被调用,因此,设置我的值的内部回调myCallback永远不会被调用. /资源 .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); }); }); })
如上所述:
在使用$httpBackend.when设置响应后,您仍然需要调用$httpBackend.flush()来清除模拟的响应. 参考文献:http://docs.angularjs.org/api/ngMock.$httpBackend – 刷新http请求部分 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容