繁体   English   中英

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

[英]The value of the variable doesn't change after calling it in before each?

我正在使用 Jasmine 进行测试,并且遇到了 spy 实现。

我有这段代码:

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM