1

I'm using the SoundCloud JavaScript SDK with AngularJS, and trying to run Karma tests on it. I keep getting the error Error: [$injector:modulerr] Failed to instantiate module SoundcloudApp due to: ReferenceError: Can't find variable: SC when I run the tests.

The variable SC (provided by the SoundCloud API, when including the script) is used in an AngularJS service:

angular.module('SoundcloudApp').provider('SoundCloud', function() {
  SC.initialize({
    clientId: 'SeES8KzD8c44J9IU8djbVg'
  });

  this.$get = function($q) {
    return {
      getUser: function(id) {
        // returns user object with a given id

        var user = $q.defer(); 


        SC.get('/users/' + id, function (userData, err) {
          if (err) {
            user.reject(err.message);
          } else {
            user.resolve(userData);
          }
        });

        return user.promise;
      }
    };
  };
});

Should I just mock this service? How do I do that?

delwin
  • 830
  • 2
  • 10
  • 15
  • Are you trying to create a mock for `SC` or a mock for the actual `Soundcloud` service? – ivarni Jul 20 '14 at 11:27
  • I want to mock the service, I suppose. I know how to do that by manually declaring a variable [as shown here](http://stackoverflow.com/a/24127144/1080586), but I'd prefer to keep the mocked service in a separate file and inject it somehow. – delwin Jul 20 '14 at 14:08
  • Just declare it on a module, e.g. `angular.module('myMocks', []).provider('SoundCloudMock', ...)` and make sure to include that file in your test config. Then use pretty much the same approach except inject the mocked service instead of creating it inline. – ivarni Jul 20 '14 at 19:10

1 Answers1

0

You can inject mocks into your service by using $provide.

You can find an explanation in the answer to this question: Injecting a mock into an AngularJS service

Community
  • 1
  • 1
Nick VN
  • 322
  • 3
  • 5
  • Only problem with that is that SC isn't injected via DI in his code, it's assumed to be available as a global variable. Unless of course I misread the question and he wants to mock the actual service and not its dependency on SC. – ivarni Jul 20 '14 at 11:23