2015-02-07 45 views
2

AngularJS中的單元測試存在一些問題。我從Github角種子應用程序中拿走並編寫了一些模塊。現在,當我嘗試測試它時,我有錯誤。 問題僅在單元測試中 - 瀏覽器應用程序工作正常。AngularJS中的單元測試錯誤 - 具有許多依賴性的控制器

我覺得應該很容易解決,但是我找不到我犯錯的地方。

我的控制器:

'use strict'; 
angular.module('myApp.student', ['ngRoute']) 

.config(['$routeProvider', function($routeProvider) { 
    $routeProvider.when('/student', { 
    templateUrl: 'student.html', 
    controller: 'StudentCtrl' 
    }); 
}]) 
.controller('StudentCtrl', ['$scope', '$http', '$modal', '$log', function($scope, $http, $modal, $log) { ... }]); 

我的單元測試dokumenty_test.js:

describe('myApp.student', function() { 
    beforeEach(module('myApp.student')); 

    describe('StudentCtrl controller', function(){ 

    it('should ....', inject(function($controller) { 
     //spec body 
     var view1Ctrl = $controller(StudentCtrl'); 
     expect(view1Ctrl).toBeDefined(); 
    })); 

    }); 
}); 

而且從控制檯錯誤: 錯誤:[$注射器:unpr]未知提供商:$ scopeProvider < - $ scope http://errors.angularjs.org/1.2.28/ $ injector/unpr?p0 =%24scopeProvider%20%3C-%20%24scope

在此先感謝

回答

2

您需要在創建時手動設置的控制器的依賴關係:

it('should ....', inject(function($controller, $rootScope, $http, $modal, $log) { 

    var view1Ctrl = $controller('StudentCtrl', { 
    '$scope': $rootScope.$new(), 
    '$http': $http, 
    '$modal': $modal, 
    '$log': $log 
    }); 

    expect(view1Ctrl).toBeDefined(); 
})); 

演示:http://plnkr.co/edit/IciIZvjRu66P3NhDc6ud

請注意,我說的模塊ui.bootstrap以來依賴於應用程序控制器正在使用$modal

你可以閱讀更多關於單元測試控制器here

+0

我添加了依賴ui.bootstrap和在karma.conf.js鏈接到ui.bootstrap:'https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.0.js'和它的工作:)謝謝! – Alburnus 2015-02-08 10:13:36

+0

不客氣:) – tasseKATT 2015-02-08 10:16:21

相關問題