2014-04-18 53 views
1

我有一個規範的是測試的,如果在範圍上的方法被調用(見下文)茉莉花測試範圍方法失敗

describe("Event Module tests", function() { 

    var scope, simpleController; 

    beforeEach(module('SimpleApplication')); 
    beforeEach(inject(function ($rootScope, $controller) { 
     scope = $rootScope.$new(); 
     simpleController = $controller("SimpleController", { 
      $scope: scope 
     }); 
    })); 


    it("Scope function should be triggered", function() { 

     spyOn(scope, "trigger"); 

     scope.trigger();//invoke the function on controller 

     expect(scope.trigger).toHaveBeenCalled();//Passes 
     expect(scope.isTriggered).toBeTruthy();//Fails 

    }); 

}); 

應用程序代碼(代碼以進行測試):

angular 
    .module("SimpleApplication", []) 
    .controller("SimpleController", function ($scope) { 

     $scope.message = "Hello World"; 

     $scope.isTriggered = false; 

     $scope.trigger = function() { 
      $scope.isTriggered = true; 
     }; 
    }); 

茉莉花報道「預計虛假是真的」。怎麼來的 ?因爲該方法將其設置爲真!

更新:

出於某種原因,SpyOn是變異我的對象的東西它的目的是爲。所以下面的一段代碼效果不錯

it("Scope function should be triggered", function() { 

      scope.trigger();//invoke the function on controller 

      expect(scope.isTriggered).toBeTruthy();//Now Passes 

     }); 
+1

對別人來說這可能很明顯,但是你意識到你可以在瀏覽器(如Chrome或Firefox)中執行單元測試,通過你的代碼來看看它在做什麼?您可以在命令行上執行Karma並使用瀏覽器中的調試器來執行此操作。 –

+0

@DavidM.Karr某種方式或其他你的建議讓我找到答案。 「Spyon」正在改變我的「觸發」功能,所以它確實沒有做到我想要的。所以刪除了那段代碼 – Deeptechtons

回答

2

spyOn不會調用你的方法。它只是間諜。如果你想讓它被調用,你必須添加一些東西: