为什么在 Jasmine 中使用 spyOn "stops all execution of a function"(要求澄清关于 Jasmine 2.2 Documentation on Spies 的信息)

Why spyOn "stops all execution of a function" in Jasmine (asking for clarification on Jasmine 2.2 Documentation on Spies)

在 Jasmine 2.2 中 documentation 我无法理解演示 Spies 基本用法的最后规范。

beforeEach() 部分我们设置 bar = null,然后我们监视 foo.setBar 然后我们调用 foo.setBar 两次。我不明白为什么在上一个规范中 bar === null 。不应该是 bar === 456 在间谍被拆毁之前吗?

示例如下:

describe("About a Spy", function(){
  var foo, bar = null;

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

    spyOn(foo, "setBar"); // we spy

    foo.setBar(123); // shouldn't bar === 123 here?
    foo.setBar(456, 'another param'); // and bar === 456 here?
  });



  it("stops all execution on a function", function() {
    // What, why, how?
    expect(bar).toBeNull();

    //I expected this to be the case, but it's not.
    //expect(bar).toBe(456);
  });
});

我一定是误解了 beforeEach 是如何建立和拆除变量范围的,或者可能有一个步骤 describe 部分中的变量被重置?或者他们从未真正接触过,因为我们只使用了间谍功能而不是真正的功能?

如果你能解释一下这个规范中变量 bar 到底发生了什么,那将非常有帮助,这样我就能理解为什么它的值在最后一个规范中保持为空。

谢谢!

If you look closely, you might realize that spyOn is replacing the original function with a spy that intercepts the function calls and tracks a lot of potentially useful information about them. The problem we run into above is that once we’ve replaced the original function, we’ve lost its capabilities. We can remedy that with andCallThrough. If you chain andCallThrough() after calling spyOn, the spy will then pass any calls to it through to the original function

http://www.joezimjs.com/javascript/javascript-unit-testing-with-jasmine-part-2/