1

There are some useful libraries I want to use in angularjs, e.g. jquery, underscore, underscore.string.

It might not be a good idea to use them directly in angular code(say, controllers, directives), because it's hard to mock and test. So I want to wrap them into angular modules:

angularUnderscore.js

define(['angular', 'underscore'], function(ng, _) {
  return ng.module('3rd-libraries')
    .service('underscoreService', function() {
      return _;
    });
});

My questions are:

  1. Is it good to use .service() to define a service? Or is a factory or constant better?
  2. Is it good to use underscoreService, or just underscore is enough and better?
Freewind
  • 193,756
  • 157
  • 432
  • 708
  • a very opinionated question. just my preference : 1. service, 2. underscore – harishr Nov 05 '14 at 11:21
  • I always put those in a factory. Underscore (or better: lodash) i always treat as a little exception, as it is basically a utility-library. I never needed to mock it in any way and I actualöly use in my tests anyways... – David Losert Nov 05 '14 at 11:50

1 Answers1

1

I believe it is really a question of scope.
Although some will disagree, I think that loading _underscore as a dependency of every tests suite is just fine. The reason for that is my rule of thumb saying any "static" operation - that is - any generic algorithm used that is not application logic or data sensitive, should be tested separately (or not at all in case of _underscope like frameworks).
This makes the tests simpler to write, more readable and maintainable and putting rare cases aside, these tests will probably fail anyway if _underscore will have a new bug on sorting an array. Moreover, I can't see you benefitting (other the mocking, which I addressed before) DI of these algorithm.

However, if an algorithm is more complex and involves data logic dependency, I would definitely introduce a factory (or a service, both are singletons) just for encapsulating this logic and making it testable by itself. As far as service vs factory (vs provider), there are probably a tons of answers out there, I personally liked: This

Community
  • 1
  • 1
Tomer
  • 4,382
  • 5
  • 38
  • 48