Angular:错误:[$injector:unpr]未知提供商:$scopeProvider <- $scope

Angular: Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope

本文关键字:scopeProvider 提供商 scope 错误 injector unpr Angular 未知      更新时间:2023-09-26

关于在测试和服务中注入$scope的另一个问题:-)学习angular并使用angular-seed应用程序作为开始。

我已经扩展了我的控制器到$scope,但现在我的默认角种子测试失败了

错误:[$injector:unpr]未知提供商:$scopeProvider <- $scope

我不明白是错误与我的控制器或与我的测试…

视图/控制器/服务

(function () {
    "use strict";
    angular.module("app.view1", ["ngRoute"])
    .config(["$routeProvider",
        function ($routeProvider) {
            $routeProvider.when("/view1", {
                templateUrl: "views/view1/view1.html",
                controller: "View1Ctrl"
            });
        }
    ])
    .factory("User", ["$http",
        function ($http) {
            var User = {};
            User.get = function () {
                return $http.get("/api/v1/user");
            };
            return User;
        }
    ])
    .controller("View1Ctrl", ["$scope", "User",
        function ($scope, User) {
            User.get().success(
                function (response) {
                    $scope.user = response;
                });
        }
    ]);
}());

'use strict';
describe('app.view1 module', function() {
  beforeEach(module('app.view1'));
  describe('view1 controller', function(){
    it('should ....', inject(function($controller) {
      //spec body
      var view1Ctrl = $controller('View1Ctrl');
      expect(view1Ctrl).toBeDefined();
    }));
  });
});

应用程序正在工作,我在HTML中看到数据,但测试失败…欢迎提出建议!

我在测试中缺少$scope,这里是更新后的测试:

'use strict';
describe('app.view1 module', function() {
    beforeEach(module('app.view1'));
    describe('view1 controller', function() {
        it('should ....', inject(function($controller, $rootScope) {
            //spec body
            var $scope = $rootScope.$new(),
                ctrl = $controller('View1Ctrl', {
                    $scope: $scope,
                    $User: {} 
                });
            expect(ctrl).toBeDefined();
        }));
    });
});

您正在测试中,没有DOM,也没有$作用域。

你可以通过向$controller服务传递局部变量来处理这个问题,像这样:
  var $scope = {};
  var view1Ctrl = $controller('View1Ctrl', { $scope: $scope });