Shane
Shane

Reputation: 5687

karma: TypeError: Cannot read property 'prototype' of undefined

I get the below error, whenever i try to inject my service.

(function () {

    describe('Test', function () {

        var $scope, $state, service,ctrl;

        beforeEach(function() {
            module('moduleApp');

            module(function($provide) {
                $provide.service('AppService', service);
            });

            inject(function($rootScope,$injector,$controller,AppService) {
                $scope = $rootScope.$new();
                $state = $injector.get('$state');
                service = $injector.get('AppService');
                ctrl = $controller('MyCtrl', {
                    $scope: $scope,
                    $state: $state,
                    AppService: service
                });
            });
        });


        it('should have a working UserSession service', function() {
            expect(service).to.exist;
        });


    });

}());

Error:

TypeError: Cannot read property 'prototype' of undefined
    at Object.instantiate (bower_components/angular/angular.js:4577:82)
    at Object.<anonymous> (bower_components/angular/angular.js:4438:24)
    at Object.invoke (bower_components/angular/angular.js:4570:17)
    at Object.enforcedReturnValue [as $get] (bower_components/angular/angular.js:4422:37)
    at Object.invoke (bower_components/angular/angular.js:4570:17)
    at bower_components/angular/angular.js:4387:37
    at getService (bower_components/angular/angular.js:4529:39)
    at Object.invoke (bower_components/angular/angular.js:4561:13)
    at Context.workFn (bower_components/angular-mocks/angular-mocks.js:2524:20)
    at window.inject.angular.mock.inject (bower_components/angular-mocks/angular-mocks.js:2496:37)
Error: Declaration Location
    at window.inject.angular.mock.inject (bower_components/angular-mocks/angular-mocks.js:2489:25)
    at Context.<anonymous> (test/unit/app/views/Test.js:17:13)

Upvotes: 0

Views: 4849

Answers (1)

Mehraban
Mehraban

Reputation: 3324

What are you trying to do?! First you tell karma to use an undefined object service as AppService and then you try to get AppService from injector and assign it to service? It's a loop.

If the unit under test is AppService, there is no need for this:

module(function($provide) {
    $provide.service('AppService', service);
});

if you need the service, you can simply do this:

inject(function($rootScope,$injector,$controller, _AppService_) {
    $scope = $rootScope.$new();
    $state = $injector.get('$state');
    service = _AppService_;
    ctrl = $controller('MyCtrl', {
        $scope: $scope,
        $state: $state,
        AppService: service
    });
});

and if the unit under test depends on AppService, you first build a mock service and then use provide, and remember you don't need to inject it again.

Upvotes: 2

Related Questions