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

Unknown provider: $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();
    }));

  });
});

稍微重组您的单元测试。我们有一个模式,其中控制器在 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
      }
    }]);

这是因为当您在测试中创建它时,您没有在控制器内部传递 $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 });