未知提供商:$scopeProvider <- $scope



我正在尝试进行一个小的测试工作,以验证控制器是否定义。

我收到的错误是:

myApp.orders module Order controller should .... FAILED
Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- OrdersCtrl

阅读类似的错误,它与依赖项有关,但我不知道出了什么问题。

控制器:

'use strict';
angular.module('myApp.orders', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/orders', {
templateUrl: 'orders/orders.template.html',
controller: 'OrdersCtrl'
});
}])
.controller('OrdersCtrl', function($scope, $location) {
$scope.changeView = function(view){
$location.path(view); // path not hash
}
});

测试:

'use strict';
describe('myApp.orders module', function() {
beforeEach(module('myApp.orders'));
describe('Order controller', function(){
it('should ....', inject(function($controller) {
//spec body
var OrdersCtrl = $controller('OrdersCtrl');
expect(OrdersCtrl).toBeDefined();
}));
});
});

这是因为在测试中创建控制器时,您没有在控制器内部传递$scope变量。控制器尝试定义 $scope.changeView,但它发现$scope未定义。 您需要在测试中将 $scope 变量传递给控制器。

var $rootScope, $scope, $controller;
beforeEach(function() {
module('myApp.orders');
inject(function (_$rootScope_, _$controller_) {
$rootScope = _$rootScope_;
$scope = _$rootScope_.$new();
$controller = _$controller_;
});
});

在你的测试中,

var OrdersCtrl = $controller('OrdersCtrl', { $scope: $scope });

稍微调整你的单元测试。我们有一个模式,其中控制器在 beforeEach() 中定义,因此它已准备好进行测试。您还需要导入要测试的控制器:

import ControllerToTest from 'path/to/your/real/controller';
describe('myApp.orders module',() => {
let vm;
beforeEach(() => {
inject(($controller, $rootScope) => {
vm = $controller(ControllerToTest,
{
$scope: $rootScope.$new()
};
});
});
describe('Order Controller', () => {
it('should do something', () => {
expect(vm).toBeDefined();
});
});
});

像这样管理你的控制器

.controller('OrdersCtrl',['$scope', '$location', function($scope, $location) {
$scope.changeView = function(view){
$location.path(view); // path not hash
}
}]);

相关内容

最新更新