Stephen Collins
Stephen Collins

Reputation: 3653

Angular $injector has dependency but can't create it

I'm trying to instantiate a dependency in my Angular unit test using Angular-Mocks.

beforeEach(inject(function ($injector) {
    myService = $injector.get("commandService");
}));

If I set a breakpoint at myService = $injector.get("commandService"); and call myService = $injector.has("commandService");, it returns true, but get() throws an exception:

Uncaught Error: [$injector:undef] http://errors.angularjs.org/1.4.3/$injector/undef?p0=commandService
at Error (native)
at http://localhost:9876/base/bower/angular/angular.min.js:6:416
at Object.$get (http://localhost:9876/base/bower/angular/angular.min.js:37:127)
at Object.e [as invoke] (http://localhost:9876/base/bower/angular/angular.min.js:39:156)
at http://localhost:9876/base/bower/angular/angular.min.js:40:478
at Object.d [as get] (http://localhost:9876/base/bower/angular/angular.min.js:38:364)
at Object.eval (eval at evaluate (unknown source), <anonymous>:1:11)
at Object.InjectedScript._evaluateOn (<anonymous>:905:55)
at Object.InjectedScript._evaluateAndWrap (<anonymous>:838:34)
at Object.InjectedScript.evaluateOnCallFrame (<anonymous>:964:21)

My service has no dependencies, so I'm not sure why it can't create it.

class CommandService{

    public getCommandStatus(): any[] {
        return new Array<any>()
    }
}

angular.module('app').factory('commandService',  CommandService);

Upvotes: 0

Views: 229

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 220904

You should use the unminified Angular sources when diagnosing problems as it produces human-readable error messages:

Provider 'CommandService' must return a value from $get factory method. http://errors.angularjs.org/1.4.3/$injector/undef?p0=CommandService

Your CommandService is already a service, not a factory function for a service. Just call .service instead of .factory and you're good to go.

If you really want consumers of your service to new it themselves (odd, but OK), you could write:

class CommandService {
  constructor() {
    console.log('all ok');
  }
}
function fn() {
  return CommandService;
}

angular.module('app', []).factory('CommandService', fn);

Upvotes: 2

Related Questions