【问题标题】:how to check createSpyObj properties have been accessed如何检查 createSpyObj 属性已被访问
【发布时间】:2022-08-17 20:58:46
【问题描述】:

我试图弄清楚如何断言使用createSpyObj 创建的属性已被访问并且我遇到了砖墙。

this StackBlitz spec

describe(\'spyObjectTest\', () => {
  it(\'should create a spy object and assert it was accessed\', () => {
    const spyObj = jasmine.createSpyObj(
      \'spyObj\',
      {},
      {
        x: \'foo\',
        y: \'bar\',
        z: \'fubar\',
      }
    );

    // Spy object is accessed here...
    console.log(spyObj.x, spyObj.y, spyObj.z);

    // I get this useless error. how is x not a spy?
    // Error: <toHaveBeenCalled> : Expected a spy, but got \'foo\'.
    // Usage: expect(<spyObj>).toHaveBeenCalled() (line 5180)
    expect(spyObj.x).toHaveBeenCalled();
    expect(spyObj.y).toHaveBeenCalled();
    expect(spyObj.z).toHaveBeenCalled();
  });
});

我要做的就是检查这些应该是间谍的属性是否已被访问。有没有办法做到这一点?

    标签: jasmine karma-jasmine karma-runner


    【解决方案1】:

    不幸的是,这些属性不是间谍对象,而是作为类或对象的实例变量的属性。 Spy 对象是函数或方法,我们只能在这些对象上使用toHaveBeenCalled()

    我要做的是断言有问题的实例属性已使用这些属性进行了更新。

    所以如果代码是:

    this.x = theSpyObj.x;
    

    断言可以是:

    expect(component.x).toBe('foo');
    

    【讨论】:

      猜你喜欢
      • 2011-10-28
      • 2023-03-29
      • 1970-01-01
      • 2019-08-16
      • 2020-03-31
      • 2019-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多