为什么我不能在我的测试中创建这个控制器?

Why can't I create this controller in my test?

我的控制器似乎运行良好。我需要编写测试用例,所以我在 beforeEach() 中添加了以下内容。 $controller 被注入到 beforeEach 中,$rootScope 也是 $scope.

的来源
    createController = function() {
        var x = $controller('MyCtrl', {
            '$scope': $scope
        });
        console.log(">>>>>>", JSON.stringify(x));
        return x;
    };

当我调用 createController 时,x 记录为 {}

我检查了传入的 $scope - 它看起来不错。我故意拼错 'MyCtrl' 并收到一条合理的错误消息。

什么会导致 $controller 对象成为 return 空对象,而不记录错误?

那里没有显示错误,因为你真的没有在控制器实例上附加任何东西,所有东西都附加到范围。所以你得到一个空对象,因为毕竟控制器确实被实例化了。如果您使用 controllerAs 语法或在控制器实例上附加属性,您将能够看到它们。

angular.module('app', []).controller('ctrl', function() {
  this.name = "John";
  this.getFormattedName = function() {
    return "Hi i am " + this.name

  }

}).controller('ctrl2', function($controller) {
  var ctrl = $controller('ctrl');
  console.log(JSON.stringify(ctrl));
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl as ctrl">
  {{ctrl.getFormattedName()}}
  <div ng-controller="ctrl2"></div>
</div>

另请注意,当您使用 JSON.stringify

时,并非所有内容都会被字符串化

JSON.stringify converts a value to JSON notation representing it:

  • Properties of non-array objects are not guaranteed to be stringified in any particular order. Do not rely on ordering of properties within the same object within the stringification.
  • Boolean, Number, and String objects are converted to the corresponding primitive values during stringification, in accord with the traditional conversion semantics.
  • If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array). All symbol-keyed properties will be completely ignored, even when using the replacer function.

所以只需在您的案例中使用指定的范围,因为那最终是视图模型。

var myCtrlScope = $scope.$new(); //Create a child scope, so you keep it separate
createController = function() {
    var x = $controller('MyCtrl', {
        '$scope': myCtrlScope
    });
    console.log(">>>>>>", myCtrlScope);
    return myCtrlScope ;
};
//And use myCtrlScope to access scope methods and properties attached by instantiating the controller `MyCtrl` using the `$controller` provider.