一部のリソースを使用するサービスを使用しているディレクティブを単体テストしようとしています。私が抱えている問題get
は、リソースのメソッドをモックするとモックされますが、コールバック関数は呼び出されないことです。したがって、結果は期待されるものではありません。
ここでspyOn
提案されているように を使用してリソースをモックしようとしましたが、どちらも機能しませんでした。コードをデバッグすると、get メソッドに到達しますが、get コールバック関数は呼び出されないため、値を設定する内部コールバックは呼び出されません。私のアプローチが正しいかどうかはわかりませんが、あなたの提案に感謝します。$httpBackend.when
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);
});
});
})