У меня есть служба, которая просматривает текущий URL-адрес и извлекает параметр querystring:
app.service('myService', function($location) {
return {
getCustID : function() {
return $location.search().custID;
}
};
});
И я смог успешно выполнить тестирование через:
describe('myService', function(){
var $location, myService;
beforeEach(module('myApp'));
beforeEach(inject(function (_myService_, _$location_) {
this.myService = _myService_;
$location = _$location_;
}));
it('should get a promoCode from the url', function(){
$location.url('/?custID=DSGAG444355');
expect(this.myService.getCustID()).toEqual('DSGAG444355');
});
});
Однако у меня есть директива, которая использует вышеприведенную службу. Как я могу проверить это?
Директива:
app.directive('imageDirective', function($compile, myService) {
return {
restrict: 'A',
replace: true,
scope: true,
link: function (scope, element, attrs) {
var custID = myService.getCustID();
var myText;
if (custID == 3) {
text = 'cust ID is 3';
}
var jqLiteWrappedElement = angular.element('<img src="/resources/img/welcome.png' alt=" ' + myText + '" />');
element.replaceWith(jqLiteWrappedElement);
$compile(jqLiteWrappedElement)(scope);
}
};
});
ОБНОВИТЬ:
Здесь тест, который я попытался сделать, основываясь на внутреннем ответе ниже:
описать ('my test test', function() {var $ scope, compile, element, myMock;
beforeEach(module('myApp'));
beforeEach(module(function($provide){
myMock = {}//Mock the service using jasmine.spyObj, or however you want
$provide.factory('myService', function(){
return myMock;
})
}));
beforeEach(inject(function ($rootScope, $compile) {
$scope = $rootScope.$new();
element = angular.element("<img my-directive/>");
$compile(element)($scope);
$scope.$digest();
}));
it('should get a parameter from the URL', function(){
$location.url('/?custID=003');
expect(myMock.getcustID()).toEqual('003');
});
beforeEach(module('myApp'));
beforeEach(module(function($provide){
myMock = {}//Mock the service using jasmine.spyObj, or however you want
$provide.factory('myService', function(){
return myMock;
})
}));
beforeEach(inject(function ($rootScope, $compile) {
$scope = $rootScope.$new();
element = angular.element("<img my-directive/>");
$compile(element)($scope);
$scope.$digest();
}));
it('should get a parameter from the URL', function(){
$location.url('/?custID=003');
expect(myMock.getcustID()).toEqual('003');
});
}); });
TypeError: myService.getCustID is not a function
Используйте Jasmine mocks для модульного тестирования. После загрузки библиотеки:
describe('mydirective', function(){
var $location, myService;
beforeEach(module('myApp'));
beforeEach(inject(function (_myService_, _$location_) {
myService = _myService_;
$location = _$location_;
spyOn(myService, "getCustID").and.returnValue("123462");
}));
//Write stuff for your directive here
it('should have made a call to ', function(){
expect(myService.getCustId).toHaveBeenCalled()
});
для дополнительной справки: http://volaresystems.com/blog/post/2014/12/10/Mocking-calls-with-Jasmine
Вы можете издеваться над сервисом, используя $provide
var myMock;
beforeEach(module('myApp'));
beforeEach(module(function($provide){
myMock = {}//Mock the service using jasmine.spyObj, or however you want
$provide.factory('myService', function(){
return myMock;
})
}));
а затем следуйте инструкциям по угловой документации о том, как указывать единицы измерения.
myMock = jasmine.createSpyObj('myServiceMock', ['getCustID',/*etc all the functions yo want to mock*/ ])