茉莉花间谍的例子如何运作

Kua*_*uan 2 testing jasmine

所有;

我刚刚开始学习Jasmine(版本2.0.3),当我到Spies部分时,第一个例子让我很困惑:

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();
  });
});
Run Code Online (Sandbox Code Playgroud)

我想知道是否有人能解释为什么setBar函数不会影响describe块中定义的bar?茉莉花间谍如何处理这件事?

谢谢

Cac*_*nta 5

因为您实际上并没有执行这些方法.

如果您希望此测试失败:

it("stops all execution on a function", function() {
    expect(bar).toBeNull();
});
Run Code Online (Sandbox Code Playgroud)

在这些电话之后:

foo.setBar(123);
foo.setBar(456, 'another param');
Run Code Online (Sandbox Code Playgroud)

然后你应该打电话and.callThrough给你的间谍.

spyOn(foo, 'setBar').and.callThrough();
Run Code Online (Sandbox Code Playgroud)

文档中

间谍:and.callThrough

通过使用and.callThrough链接间谍,间谍仍将跟踪对它的所有调用,但此外它将委托给实际的实现.

关于你的问题,"茉莉如何处理这个问题?"

这里你可以阅读一个基本的解释:

模拟通过实现代理模式来工作.创建模拟对象时,它会创建一个代替真实对象的代理对象.然后我们可以在我们的测试方法中定义调用哪些方法及其返回值.然后可以使用模拟来检索间谍功能的运行时统计信息,例如:

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.
Run Code Online (Sandbox Code Playgroud)

如果你希望所有的实现细节,你可以检查茉莉花源代码是开源 :)

在这个源文件CallTracker中,您可以看到如何收集有关方法调用的数据.

关于代理模式的更多信息.