在每个变量之前调用它之后,变量的值不会改变吗?

时间:2019-07-18 13:49:59

标签: javascript jasmine

我正在与Jasmine进行测试,并且遇到了间谍实施。

我有这段代码:

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

  beforeEach(function() {
    foo = {
      setBar: function(value) {
        bar = value;
      }
    };
    spyOn(foo, 'setBar');
    foo.setBar(123);
    foo.setBar(456, 'another param');
    console.log(bar)
  });

  it("tracks all the arguments of its calls", function() {
    expect(foo.setBar).toHaveBeenCalledWith(123);
    expect(foo.setBar).toHaveBeenCalledWith(456, 'another param');
    expect(bar).toBeNull(); /* Why is this NULL it should be 456 because it the last value we called our function with!!!*/
  });
});

我添加了此评论/* Why is this NULL it should be 456 !!!*/只是为了澄清我不明白的内容。 因为此代码:

let bar1 = null
let foo1 = {
      setBar: function(value) {
        bar1 = value;
      }
    }
     foo1.setBar(123);
    foo1.setBar(456, 'another param');
    console.log(bar1) // 456

打印456

1 个答案:

答案 0 :(得分:2)

如果在某个函数(此处为foo.setBar)上启用了spyOn,则默认情况下jasmine不会调用实际函数,它只会跟踪详细信息。

如果要调用实际函数,则必须指定spyOn(foo, 'setBar').and.callThrough();,而不仅仅是spyOn(foo, 'setBar')

此后,您可以观察到expect(bar).toBeNull()将失败而expect(bar).toBe(456)将成功。