【问题标题】:Jasmine: Testing whether a method is called by another method from another classJasmine:测试一个方法是否被另一个类的另一个方法调用
【发布时间】:2019-01-07 15:02:19
【问题描述】:

我有 2 个类如下

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

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

我尝试使用以下测试来测试 B 类中的方法 b(),但测试不工作

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()
  })
})

我是不是误解了 jasmine 的测试概念? 我也试过`jasmine.createSpy',它也不起作用

附:我确实尝试过手动测试并确认已调用 B 类的方法 b()

【问题讨论】:

  • a.run() 不是间谍。你的意思是写‘expect(b.b).toHaveBeenCalled()’吗?你也可以用类似‘spyOn(a, ‘run’).and.callThrough()’之类的东西进行不同的设置
  • @dmcgrandle 抱歉打错了是的,我的意思是写 expct (b.b).toHaveBeenCalled() 我也使用了 'spyOn(a, 'run').and.callThrough()',它也不是工作

标签: node.js typescript jasmine


【解决方案1】:

b 变量不在任何地方使用,它与a 内部的this.b 不同,因此不会调用b.b。

应该是:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    • 2015-12-15
    • 1970-01-01
    • 2016-11-16
    相关资源
    最近更新 更多