2013-09-24 56 views
6

我想通過噶瑪測試我的AngularJS應用與茉莉花。我得到這個錯誤(至少,這是最新的人):AngularJS工廠測試在噶瑪與茉莉花

Uncaught TypeError: Cannot read property '$modules' of null 
    at /Users/benturner/Dropbox/Code/galapagus/app/static/js/angular-mocks.js:1866 

從我karma.conf.js:

files: [ 
     'static/js/jquery.min.js', 
     'static/js/angular.min.js', 
     'static/js/angular-mocks.js', 
     'static/js/angular-resource.min.js', 
     'static/js/angular-scenario.js', 
     'static/js/angular-loader.min.js', 
     'static/js/momentous/ctrl_main.js', // contains all my app's code 
     'test/momentous.js' 
], 

這裏是我的測試:

(function() { 
    "use strict"; 

    var controller = null; 
    var scope = null; 

    describe("Services", inject(function($rootScope, Moments) { 
     var mockedFactory, moments, flag, spy; 
     moments = [{name: 'test'}]; 

     beforeEach(module('momentous', function($provide) { 
      scope = $rootScope.$new(); 

      $provide.value('$rootScope', scope); 

      mockedFactory = { 
       getList: function() { 
        return moments; 
       } 
      }; 
      spy = jasmine.createSpy(mockedFactory.getList); 

      $provide.value('Moments', mockedFactory); 
     })); 

     it('should return moments from the factory service', function() { 
      runs(function() { 
       console.log(scope.getList); 
       flag = false; 
       setTimeout(function() { 
        scope.getList(); 
        flag = true; 
       }, 500); 
      }); 

      waitsFor(function() { 
       return flag; 
      }, "The call is done", 750); 

      runs(function() { 
       expect(scope.moments).toEqual([{name: 'test'}]); 
       expect(spy).toHaveBeenCalled(); 
      }); 
     }); 
    })); 

}()); 

所以我試圖做的是模擬我的工廠服務,並檢查它是否返回一個對象數組並將其設置爲$ scope中的一個變量。我們不得不使用runs()和waitsFor()方法。

我仍然不明白我是如何注入我的$範圍,以便我可以測試它,並與angular-mocks.js現在給我一個錯誤,我覺得我越來越解決這個問題,而不是接近。

我從各種文檔,指南和stackoverflow的答案拼湊在一起。任何指導?謝謝。

回答

10

我也堅持得到這個確切的錯誤。我的代碼類似於我試圖測試提供程序,所以我調用模塊並將它傳​​遞給配置提供程序的函數。

解決:

我發現這個問題是由於調用「注入」到委託返回到「描述」的方法。您只能使用注入來將委託返回給它。

例如:

describe('something', inject(function(something) {})); // will throw the $module is null error 

但是這將工作:

it('something', inject(function(something) {})); // works :) 
+0

'注入()'也可以在'beforeEach()'通話。 –

+2

所以這沒有解決。有些理解的人應該解釋爲什麼在閱讀所有各種文檔時要理解它是令人困惑的。 –