【问题标题】:How to add a method into rootScope from the rootScope from another controller in an Angular unit test?如何在Angular单元测试中从另一个控制器的rootScope将方法添加到rootScope?
【发布时间】:2016-05-17 21:25:49
【问题描述】:

我正在对从另一个控制器调用 $rootScope 方法的函数进行单元测试。有没有办法将该功能添加到我要测试的控制器的 $rootScope 中?我正在使用包含 Jasmine、Karma、PhantomJS 等的测试环境。

【问题讨论】:

  • 使用$rootScope 是一种反模式。您应该考虑为共享功能创建服务。

标签: javascript angularjs jasmine


【解决方案1】:

如果您想在测试中手动添加方法,您可以使用 Jasmine 的 beforeEach() 在测试运行之前设置模拟/实现方法,因此通过使用 inject() 您可以传入 $rootScope 并设置您的方法

【讨论】:

    【解决方案2】:

    由于 $rootScope 在你的所有控制器之间共享,你可以直接在 $rootScope 对象中定义你的函数,考虑把函数定义 在 app.run 处理程序中,否则,您必须确保为要定义的函数加载了控制器,下面的示例显示了这两种方法:

    <div ng-app="myApp">
    
    <div ng-controller="Ctrl1">
      <h1>Controller 1</h1>
      <button ng-click="myFunc()">Test $rootScope.myFunc()</button>
      <button ng-click="toBeDefniendinCtrl1()">Test $rootScope.toBeDefniendinCtrl1()</button>
    </div>
    
    <div ng-controller="Ctrl2">
       <h1>Controller 2</h1>
      <button ng-click="myFunc()">Test $rootScope.myFunc()</button>
      <button ng-click="toBeDefniendinCtrl1()">Test $rootScope.toBeDefniendinCtrl1()</button>
    </div>
    
    </div>
    <script>
    var app = angular.module('myApp', []);
    app.run(function($rootScope){
      $rootScope.myFunc = function (){ alert("hi"); }
      $rootScope.toBeDefniendinCtrl1 = null;
    })  
    app.controller('Ctrl1', function($scope, $rootScope) {
      $rootScope.toBeDefniendinCtrl1 = function (){ alert("hello from Ctrl1"); }   
    });
    
    app.controller('Ctrl2', function($scope, $rootScope) {
    
    
    });
    </script>
    

    查看工作示例:http://jsbin.com/xiyozitage/edit?html,output

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多