【问题标题】:Testing current value of a property in Jasmine在 Jasmine 中测试属性的当前值
【发布时间】:2018-04-24 12:00:09
【问题描述】:

如何在 Jasmine 中进行测试:

buffer: number[] = [];

initP(): void {
    if (this.buffer.length) {
      this.buffer = [];
    }
    this.buffer = this.buffer.concat([27, 64]);
  }

我试图像这样传递当前值:

it('should initialise it', () => {
    spyOn(pService, 'initP');
    pService.initP();
    expect(buffer).toBe([27, 64]);
    expect(pService.initP).toHaveBeenCalled();
  });

问题是我收到了那个错误:

预计 [ ] 为 [ 27, 64 ]。

我正在像这样在 beforeEach 块中注入我的服务:

let pService;
let buffer: number[];

beforeEach(inject([PService], _pService => {
    pService = _pService;
    buffer = _pService.buffer;
  }));

【问题讨论】:

    标签: javascript angular unit-testing jasmine


    【解决方案1】:

    您需要添加.and.callThrough(); 以便它仍然调用原始函数。否则它不会达到initP的原始实现。

    spyOn(pService, 'initP').and.callThrough();
    

    【讨论】:

    • 是的,我现在可以看到进度了。但仍然出现错误:预期 [27, 64] 为 [27, 64]。该值似乎相同,但不适用于 toBe()。我应该使用 toEqual() 吗?
    • 是的,您需要使用toEqual。 toBe 检查它们是否是完全相同的对象引用
    • 啊,所以 toBe() 总是布尔值...谢谢!
    猜你喜欢
    • 2015-10-10
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 2019-12-31
    • 1970-01-01
    • 2017-05-30
    • 2010-11-12
    • 2020-09-05
    相关资源
    最近更新 更多