2014-12-24 56 views
9

這裏是我的2個文件和錯誤。我正在運行Karma,這是我的karma.conf.js:https://gist.github.com/devanp92/a87c0bcc2bf5b8e17f64。運行「業力開始」後,我得到這個錯誤。這是一個非常簡單的測試文件(或者我假設),我仍然遇到這些錯誤。錯誤Karma'undefined'範圍變量在beforeEach

Main.js - 這是一個控制器

angular.module('SSLApp').controller('MainCtrl', 
    function($scope, $rootScope) { 
    $scope.thing = 1; 
}); 

MainSpec.js - 這是我的測試文件

describe('MainCtrl', function() { 
var controller, scope; 

beforeEach(angular.module('SSLApp')); 

beforeEach(inject(function($controller, $rootScope) { 
    scope = $rootScope.$new(); 
    controller = $controller('MainCtrl', { 
     $scope: scope 
    }); 
})); 

it('should have scope to be defined', function(scope) { 
    expect(scope).toBeDefined(); 
}); 

}); 

錯誤!它看起來像它被稱爲undec中var MainCtrl = $控制器...

TypeError: 'undefined' is not a function (evaluating 'queueableFn.fn.call(self.userContext)') 
     at /Users/BLAH/Documents/node_modules/karma-jasmine/lib/adapter.js:184 
     at `http://localhost:9876/karma.js:185` 
     at `http://localhost:9876/context.html:53` 
    Error: [ng:areq] Argument 'MainCtrl' is not a function, got undefined 
    http://errors.angularjs.org/1.3.8/ng/areq?p0=MainCtrl&p1=not%20a%20function%2C%20got%20undefined 
     at assertArg (/Users/BLAH/Documents/node_modules/angular/angular.js:1577) 
     at assertArgFn (/Users/BLAH/Documents/node_modules/angular/angular.js:1588) 
     at /Users/BLAH/Documents/node_modules/angular/angular.js:8418 
     at /Users/BLAH/Documents/test/controllers/MainSpec.js:9 
     at invoke (/Users/BLAH/Documents/node_modules/angular/angular.js:4182) 
     at workFn (/Users/BLAH/Documents/node_modules/angular-mocks/angular-mocks.js:2350) 
     at /Users/BLAH/Documents/node_modules/karma-jasmine/lib/adapter.js:184 
     at http://localhost:9876/karma.js:185 
     at http://localhost:9876/context.html:53 
    undefined 
    Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL. 
PhantomJS 1.9.8 (Mac OS X): Executed 1 of 1 (1 FAILED) ERROR (4.999 secs/5.012 secs) 

回答

14

你在測試代碼中有兩個錯誤。

首先你用錯了模塊函數。 angular.module()函數提供了一個真正的框架模塊,而 簡單模塊()angular.mock.module()的別名,您應該在測試中使用它。所以,你應該寫你的beforeEach功能如下:

beforeEach(module('SSLApp')); 

再說了,你一個參數定義的測試案例的功能,但它應該是參數的。 scope變量可以從外部範圍訪問。

it('should have scope to be defined', function() { 
    expect(scope).toBeDefined(); 
}); 
+0

謝謝!這解決了它! – user2874945

+3

對於那些使用webpack配置運行業務的人,我推薦使用'angular.mock.module'而不是'module',因爲全局'module'將指向節點的模塊。 – brunocoelho