2013-11-14 103 views
1

我有一個單元測試,看起來像這樣

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 

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

然而,當我「注入(函數($ rootScope){..」正如我上面顯示,我得到以下錯誤(使用因果報應和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_components/angular-mocks/angular-mocks.js:2072) 
    at /dev/myapp/test/spec/interceptors/my-interceptor.js:67 
    .... 
+1

我的問題是潛在的相關:http://stackoverflow.com/questions/15416006/how-do-i-inject-rootscope-in​​to-an-angularjs-unit-test –

回答

5

我不覺得打電話describe時注入的作品我有我從我的describe呼叫移動注入到beforeEach解決了同樣的錯誤致電:

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

您可以有多個beforeEach,所以只需在現有的beforeEach以上添加這一個即可。

+2

但由於某些原因,你不能這樣做:beforeEach (注入(函數($ rootScope,$提供){...} –