Testing Services

26 views
Skip to first unread message

George Maggessy

unread,
Jan 16, 2015, 1:35:26 PM1/16/15
to ang...@googlegroups.com
Hi Gurus,

I'm a total newbie on AngularJs and my question is certainly simple. I'm trying to test a service that has a decorated $log as a parameter. What would be the right approach? Mock the $log.getInstance() function or inject the decorated implementation into the test?

define(['angular'], function(angular) {
   'use strict';

   angular.module('myApp.services.MyApi', [])
      .factory('MyApi', function($q, $log) {
            $log = $log.getInstance('VimApi');
            init = function() {
                ...
            };

         // Public API
         return {
            init: init
         };
      });
});


define(['angular', 'angular-mocks', 'app'], function(angular, mocks, app) {
   'use strict';

   describe('Service: myApi', function () {

      var myApi;

      beforeEach(function() {

         //Mock getInstance?

         module('myApp.services.MyApi');
         inject(function ($log, _MyApi_) {
            myApi = _MyApi_;
         });
      });

      it('should initialize', function () {
         expect(!!myApi).toBe(true);
      });

   });
});


Any help is appreciated.

Cheers,
George


Garry Taylor

unread,
Jan 17, 2015, 1:49:12 PM1/17/15
to ang...@googlegroups.com

George Maggessy

unread,
Jan 19, 2015, 11:54:26 AM1/19/15
to ang...@googlegroups.com
Hi Garry,

Thanks for your help.

I added the basicService example to my project just for sanity check and it worked. 

However, I'm using a decorated $log. That is, I need not only to inject $log, but also augment its methods.

For instance, I have a getInstance function on $log, which I'm injecting on my tests using the code below.

beforeEach(function() {
         module('esxUiApp.services.VimApi', function($provide) {
            var MockLog = {
               getInstance: jasmine.createSpy('getInstance')
            };
            $provide.value('$log', MockLog);
         });
      });

And as you can imagine, tests fail when it finds any other native method on $log, such as debug().

I also thought about mocking the whole $log object, but I'd like to see the logs in my test output.

Any ideas?

Cheers,
George 



Best,
George Maggessy

On Sat, Jan 17, 2015 at 10:49 AM, Garry Taylor <gplt...@gmail.com> wrote:

--
You received this message because you are subscribed to a topic in the Google Groups "AngularJS" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/angular/BOnr3jDD63g/unsubscribe.
To unsubscribe from this group and all its topics, send an email to angular+u...@googlegroups.com.
To post to this group, send email to ang...@googlegroups.com.
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages