我正在尝试对使用使用某些资源的服务的指令进行单元测试.我遇到的问题是,当我模拟我的资源的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请求部分
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。