Reputation: 8663
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
Upvotes: 0
Views: 1083
Reputation: 180
Use Jasmine mocks for unit testing. Once the library is downloaded:
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()
});
for more reference :http://volaresystems.com/blog/post/2014/12/10/Mocking-calls-with-Jasmine
Upvotes: 0
Reputation: 3586
You can mock the service using $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;
})
}));
and then follow the instructions on angular's documentation on how to unit test directives.
Upvotes: 0