2015-09-10 50 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