Testing AngularJS Services with Dependencies

I have problems testing a simple service in AngularJS, which depends on another service.

The service looks something like this:

serviceModule.factory('filtersService', ['$rootScope', 'urlService', function($rootScope, urlService){ return { getFilters: function(){ if(urlService.getPathName() == "test") { return "something"; } }]); 

In the beginning, I just tried using window.location.pathname instead of creating a service, but it seemed like it was the wrong way to trick it. So I created urlService, which basically is a simple wrapper around an object window.

Then I have my ServiceTest filters, which looks like this:

 describe('filtersService test', function(){ var filtersService, urlServiceMock; beforeEach(module('App.services')); beforeEach(function(){ urlServiceMock = { getPathName: function(){ return ""; } }; module(function($provide){ $provide.value('urlService', urlServiceMock); }); }); it('Should return something if url is test', inject(function(filtersService){ urlServiceMock = { getPathName: function(){ return "test"; } }; expect(filtersService.getFilters()).not.toBe("something"); })); }); 

But this does not seem to work. I cannot reload urlServiceMock before it starts. I can change the " beforeEach " each so that getPathName returns "test", but then I could not test the script where the URLs are not equal to the test.

+4
source share
1 answer

You can monitor the service in your test suite to change the behavior:

 spyOn(yourService, 'methodName'); 

JsFiddle has a great example of how to implement a spy: http://jsfiddle.net/robinroestenburg/aDwva/

This should allow you to work properly.

0
source

Source: https://habr.com/ru/post/1486377/


All Articles