Jasmine: Testing whether a method is called by another method from another class

夙愿已清 提交于 2019-12-24 00:24:40

问题


I have 2 classes as below

class B {
  public b() { return 1 }
}

class A {
  b: B = new B()
  public run() { return this.b.b() }
}

I tried to use the following test to test did method b() from class B, but the test is not working

describe('A spy', () => {
  let a: A
  let b: B

  beforeEach(() => {
    a = new A()
    b = new B()
    spyOn(b, 'b')

    a.run()
  })

  it('tracks that the spy was called', () => {
    expect(b.b).toHaveBeenCalled()
  })
})

Did i misunderstood jasmine's testing concept? i also tried `jasmine.createSpy', its also not working

P.S. i did tried to test it manually and confirmed that the method b() from class B had been called


回答1:


b variable isn't used anywhere, it isn't same object as this.b inside a, so b.b isn't called.

It should be:

a = new A()
spyOn(a.b, 'b')
a.run()

expect(a.b.b).toHaveBeenCalled()


来源:https://stackoverflow.com/questions/54068845/jasmine-testing-whether-a-method-is-called-by-another-method-from-another-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!