admin管理员组

文章数量:1426507

I have a unit test that looks like this

describe('Interceptor: myInterceptor', inject(function($rootScope){
    var rootScope, routeParams = { id: null };

    beforeEach(module('MyApp', function ($provide) {
        $provide.factory('$routeParams', function () {   // mock $routeParams
            return routeParams;
        });

        rootScope = $rootScope.$new();
        $provide.value('$rootScope', rootScope);         // mock $rootScope

    }));
    ....
}));

However when I do "inject(function($rootScope){ .." as I have shown above, I get the following error (using Karma and PhantomJS):

PhantomJS 1.9.2 (Mac OS X) Interceptor: myInterceptor encountered a declaration exception FAILED
TypeError: 'null' is not an object (evaluating 'currentSpec.$modules')
    at workFn (/dev/myapp/app/bower_ponents/angular-mocks/angular-mocks.js:2072)
    at /dev/myapp/test/spec/interceptors/my-interceptor.js:67
    ....

I have a unit test that looks like this

describe('Interceptor: myInterceptor', inject(function($rootScope){
    var rootScope, routeParams = { id: null };

    beforeEach(module('MyApp', function ($provide) {
        $provide.factory('$routeParams', function () {   // mock $routeParams
            return routeParams;
        });

        rootScope = $rootScope.$new();
        $provide.value('$rootScope', rootScope);         // mock $rootScope

    }));
    ....
}));

However when I do "inject(function($rootScope){ .." as I have shown above, I get the following error (using Karma and PhantomJS):

PhantomJS 1.9.2 (Mac OS X) Interceptor: myInterceptor encountered a declaration exception FAILED
TypeError: 'null' is not an object (evaluating 'currentSpec.$modules')
    at workFn (/dev/myapp/app/bower_ponents/angular-mocks/angular-mocks.js:2072)
    at /dev/myapp/test/spec/interceptors/my-interceptor.js:67
    ....
Share Improve this question edited Nov 14, 2013 at 13:35 Jeanluca Scaljeri asked Nov 14, 2013 at 12:20 Jeanluca ScaljeriJeanluca Scaljeri 29.3k66 gold badges235 silver badges383 bronze badges 1
  • 1 My question is potentially related: stackoverflow./questions/15416006/… – Gregory Avery-Weir Commented Aug 11, 2014 at 20:56
Add a ment  | 

1 Answer 1

Reset to default 5

I don't think injection works when calling describe. I had the same error which I solved by moving the injection from my describe call to a beforeEach call:

var rootScope;
beforeEach(inject(function ($rootScope) {
    rootScope = $rootScope.$new();
}));

You can have multiple beforeEach, so just add this one above your existing beforeEach.

本文标签: javascriptangularjs how to mock rootScope in unit testStack Overflow