I have a service that looks at the current URL and retrieves a querystring parameter:
app.service('myService', function($location) {
return {
getCustID : function() {
return $location.search().custID;
}
};
});
And I have been able to successfully unit test via:
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');
});
});
However, I have a directive which uses the service above. How can I test that?
Directive:
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);
}
};
});
UPDATE:
Here's a test i attempted based on the intial repsonse below:
describe('my directive 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');
});
});
TypeError: myService.getCustID is not a function