2015-09-10 51 views
1

全部;茉莉花間諜如何工作

我剛開始學習茉莉花(2.0.3版本),當我到間諜節,第一個例子讓我感到困惑:

describe("A spy", function() { 
    var foo, bar = null; 

    beforeEach(function() { 
    foo = { 
     setBar: function(value) { 
     bar = value; 
     } 
    }; 

    spyOn(foo, 'setBar'); 

    foo.setBar(123); 
    foo.setBar(456, 'another param'); 
    }); 

    it("tracks that the spy was called", function() { 
    expect(foo.setBar).toHaveBeenCalled(); 
    }); 

    it("tracks all the arguments of its calls", function() { 
    expect(foo.setBar).toHaveBeenCalledWith(123); 
    expect(foo.setBar).toHaveBeenCalledWith(456, 'another param'); 
    }); 

    it("stops all execution on a function", function() { 
    expect(bar).toBeNull(); 
    }); 
}); 

我不知道是否有人能解釋爲什麼setBar功能不影響塊內定義的塊吧?茉莉花間諜如何處理這件事?

謝謝

回答

4

因爲你實際上並沒有執行這些方法。

如果你想測試失敗:

it("stops all execution on a function", function() { 
    expect(bar).toBeNull(); 
}); 

這些調用後:

foo.setBar(123); 
foo.setBar(456, 'another param'); 

那麼你應該叫and.callThrough您的間諜。

spyOn(foo, 'setBar').and.callThrough(); 

documentation

間諜:and.callThrough

通過鏈接與and.callThrough間諜,間諜仍然會跟蹤所有 調用它,但除了它將委託給實際的 實施。

關於你的問題,'茉莉花怎麼處理這個?'

here你可以讀一個基本的解釋:

通過實現代理模式嘲弄工作。當您創建一個模擬對象時,它會創建一個代理對象,以取代實際的對象 。然後,我們可以定義在我們的測試方法中調用了哪些方法以及返回的值 。然後嘲弄可以用來 檢索在暗中監視功能運行時的統計數據,如:

How many times the spied function was called. 
What was the value that the function returned to the caller. 
How many parameters the function was called with. 

如果你希望所有的實現細節,你可以檢查茉莉花源代碼,這是Open Source :)

在此源文件CallTracker中,您可以看到有關該方法調用的收集數據的方式。

多一點關於the proxy pattern

+1

謝謝,最讓我感興趣的是茉莉花如何實現這一點,而無需運行實際功能並影響變量?基本上它是如何將所有東西都複製到其獨立的範圍內(如果我對此的理解是正確的)?你能給我更詳細的介紹嗎? – Kuan

+0

讓我更新一些更多的信息。 –

+0

謝謝,我閱讀http://www.tutorialspoint.com/design_pattern/proxy_pattern。htm根據我的理解,它基本上是使用一個內部對象來委託一個任務。但我有點想知道如何將我的例子與這種模式聯繫起來。 – Kuan