簡體   English   中英

如何在Angular單元測試中從另一個控制器的rootScope向rootScope添加方法?

[英]How to add a method into rootScope from the rootScope from another controller in an Angular unit test?

我正在對從另一個控制器調用$ rootScope方法的函數進行單元測試。 有沒有一種方法可以將該功能添加到我要測試的控制器的$ rootScope中? 我正在使用包括Jasmine,Karma,PhantomJS等的測試環境。

如果要在測試中手動添加方法,則可以在運行測試之前使用Jasmine的beforeEach()設置模擬 /實現方法,因此可以使用inject()傳入$rootScope並設置方法

由於$ 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,輸出

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM